作者 唐旭辉

添加邮件发送

package goemail
import (
"bytes"
"encoding/base64"
"fmt"
"net/smtp"
"strings"
"time"
)
type EmailHeader struct {
Key string
Value string
}
type EmailMessage struct {
FromEmail string //发件人邮箱地址
Header []EmailHeader //TODO
Toers []string //邮件接收人,如有多个,则以英文逗号(“,”)隔开,不能为空
Subject string //主题
BodyContentType string
Body []byte //内容
//TODO Copyers []string //邮件抄送人,如有多个,则以英文逗号(“,”)隔开,不能为空
//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) 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=utf-8\r\n\r\n", e.BodyContentType))
buf.Write(e.Body)
buf.WriteString("\r\n")
buf.WriteString("--" + boundary + "--")
//TODO添加附件
return buf.Bytes()
}
// func (e *EmailMessage) To() []string {
// return e.Toers
// }
func NewHtmlEmail() *EmailMessage {
return nil
}
func (e *EmailMessage) AddHeader(key string, value string) EmailHeader {
newHeader := EmailHeader{Key: key, Value: value}
e.Header = append(e.Header, newHeader)
return newHeader
}
// ServerHost string //邮箱服务器地址
// ServerPort int //邮箱服务器的端口
// FromPasswd string //发件人邮箱密码
func NewSmtpAuth(fromEmail string, pwd string, host string) smtp.Auth {
return smtp.PlainAuth("", fromEmail, pwd, host)
}
func Send(addr string, auth smtp.Auth, m *EmailMessage) error {
return smtp.SendMail(addr, auth, m.FromEmail, m.Toers, m.Bytes())
}
... ...