作者 唐旭辉

添加邮件发送

  1 +package goemail
  2 +
  3 +import (
  4 + "bytes"
  5 + "encoding/base64"
  6 + "fmt"
  7 + "net/smtp"
  8 + "strings"
  9 + "time"
  10 +)
  11 +
  12 +type EmailHeader struct {
  13 + Key string
  14 + Value string
  15 +}
  16 +
  17 +type EmailMessage struct {
  18 + FromEmail string //发件人邮箱地址
  19 + Header []EmailHeader //TODO
  20 + Toers []string //邮件接收人,如有多个,则以英文逗号(“,”)隔开,不能为空
  21 + Subject string //主题
  22 + BodyContentType string
  23 + Body []byte //内容
  24 + //TODO Copyers []string //邮件抄送人,如有多个,则以英文逗号(“,”)隔开,不能为空
  25 + //TODO附加
  26 +}
  27 +
  28 +func (e *EmailMessage) AddToer(v string) {
  29 + e.Toers = append(e.Toers, v)
  30 +}
  31 +
  32 +func (e *EmailMessage) SetBody(v []byte) {
  33 + e.Body = v
  34 +}
  35 +func (e *EmailMessage) Bytes() []byte {
  36 + buf := bytes.NewBuffer(nil)
  37 + buf.WriteString(fmt.Sprintf("From:%s \r\n", e.FromEmail))
  38 + t := time.Now().Format(time.RFC1123Z)
  39 + buf.WriteString(fmt.Sprintf("Date:%s \r\n", t))
  40 + buf.WriteString(fmt.Sprintf("To:%s \r\n", strings.Join(e.Toers, ",")))
  41 + var subject = "=?UTF-8?B?" + base64.StdEncoding.EncodeToString([]byte(e.Subject)) + "?="
  42 + buf.WriteString("Subject: " + subject + "\r\n")
  43 + buf.WriteString("MIME-Version: 1.0\r\n")
  44 + //TODO 添加header
  45 + boundary := "THIS_IS_BOUNDARY"
  46 + buf.WriteString("Content-Type: multipart/mixed; boundary=" + boundary + "\r\n")
  47 + buf.WriteString("\r\n--" + boundary + "\r\n")
  48 + buf.WriteString(fmt.Sprintf("Content-Type: %s; charset=utf-8\r\n\r\n", e.BodyContentType))
  49 + buf.Write(e.Body)
  50 + buf.WriteString("\r\n")
  51 + buf.WriteString("--" + boundary + "--")
  52 + //TODO添加附件
  53 + return buf.Bytes()
  54 +}
  55 +
  56 +// func (e *EmailMessage) To() []string {
  57 +// return e.Toers
  58 +// }
  59 +func NewHtmlEmail() *EmailMessage {
  60 + return nil
  61 +}
  62 +
  63 +func (e *EmailMessage) AddHeader(key string, value string) EmailHeader {
  64 + newHeader := EmailHeader{Key: key, Value: value}
  65 + e.Header = append(e.Header, newHeader)
  66 + return newHeader
  67 +}
  68 +
  69 +// ServerHost string //邮箱服务器地址
  70 +// ServerPort int //邮箱服务器的端口
  71 +// FromPasswd string //发件人邮箱密码
  72 +func NewSmtpAuth(fromEmail string, pwd string, host string) smtp.Auth {
  73 + return smtp.PlainAuth("", fromEmail, pwd, host)
  74 +}
  75 +func Send(addr string, auth smtp.Auth, m *EmailMessage) error {
  76 + return smtp.SendMail(addr, auth, m.FromEmail, m.Toers, m.Bytes())
  77 +}