message.go
1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package goemail
import (
"bytes"
"encoding/base64"
"fmt"
"strings"
"time"
)
type EmailHeader struct {
Key string
Value string
}
type EmailMessage struct {
FromEmail string //发件人邮箱地址
// Header []EmailHeader
Toers []string //邮件接收人,如有多个,则以英文逗号(“,”)隔开,不能为空
Subject string //主题
BodyContentType string //默认值text/html
BodyCharset string //字符编码设定默认utf-8
Body []byte //邮件正文内容
//TODO 添加附件
}
func (e *EmailMessage) AddToer(v string) {
e.Toers = append(e.Toers, v)
}
func (e *EmailMessage) SetBody(v []byte) {
e.Body = v
}
func (e *EmailMessage) SetBodyContentType(v string) {
e.BodyContentType = v
}
func (e *EmailMessage) SetBodyCharset(v string) {
e.BodyCharset = v
}
func (e *EmailMessage) Bytes() []byte {
buf := bytes.NewBuffer(nil)
buf.WriteString(fmt.Sprintf("From:%s \r\n", e.FromEmail))
t := time.Now().Format(time.RFC1123Z)
buf.WriteString(fmt.Sprintf("Date:%s \r\n", t))
buf.WriteString(fmt.Sprintf("To:%s \r\n", strings.Join(e.Toers, ",")))
var subject = "=?UTF-8?B?" + base64.StdEncoding.EncodeToString([]byte(e.Subject)) + "?="
buf.WriteString("Subject: " + subject + "\r\n")
buf.WriteString("MIME-Version: 1.0\r\n")
//TODO 添加header
boundary := "THIS_IS_BOUNDARY"
buf.WriteString("Content-Type: multipart/mixed; boundary=" + boundary + "\r\n")
buf.WriteString("\r\n--" + boundary + "\r\n")
buf.WriteString(fmt.Sprintf("Content-Type: %s; charset=%s\r\n\r\n", e.BodyContentType, e.BodyCharset))
buf.Write(e.Body)
buf.WriteString("\r\n")
buf.WriteString("--" + boundary + "--")
//TODO添加附件
return buf.Bytes()
}
// func (e *EmailMessage) AddHeader(key string, value string) EmailHeader {
// newHeader := EmailHeader{Key: key, Value: value}
// e.Header = append(e.Header, newHeader)
// return newHeader
// }