golang 发送邮件

golang发送邮件插件实现,有时候会返回错误554,有可能是主题或者内容中包含了一些被认为是垃圾的词语,换一个表达试一试。以下亲测qq邮箱和126邮箱正常。

package email

import (  
    "net/smtp"
    "strings"
)

const MAIL_HTML = "html"  
const MAIL_TEXT = "text"

type Auth struct {  
    SMTP     string // just like ip:port, e.g smtp.example.com:25
    Username string
    Password string
    auth     smtp.Auth
}

var DefaultMailSender = NewAuth("", "", "")

func NewAuth(addr string, username string, password string) *Auth {  
    var domain string
    addrStrings := strings.Split(addr, ":")
    if len(addrStrings) > 0 {
        domain = addrStrings[0]
    }
    auth := smtp.PlainAuth("", username, password, domain)
    return &Auth{
        SMTP:     addr,
        Username: username,
        Password: password,
        auth:     auth,
    }
}

func SendEmail(subject string, from string, to []string, mailType string, message string) error {  
    return DefaultMailSender.SendEmail(subject, from, to, mailType, message)
}

func (a *Auth) SendEmail(subject string, from string, to []string, mailType string, message string) error {  
    var contentType = "text/plain; charset=UTF-8"
    if mailType == MAIL_HTML {
        contentType = "text/html; charset=UTF-8"
    }
    var msg = "To: " + strings.Join(to, ",") + "\r\n" +
        "From: " + from + "\r\n" +
        "Subject: " + subject + "\r\n" +
        "Content-Type: " + contentType + "\r\n\r\n" +
        message + "\r\n"
    return smtp.SendMail(a.SMTP, a.auth, from, to, []byte(msg))
}

测试发送:

func TestSendEmail(t *testing.T) {  
    DefaultMailSender = NewAuth("smtp.126.com:25", "xxx@126.com", "xxx")

    // send text to a person.
    var err error
    err = SendEmail("golang的警报邮件", "xxx@126.com", []string{"xxx@qq.com"}, MAIL_TEXT, "你猜我能不能把邮件发送出去")
    if err != nil {
        t.Error(err)
        return
    }

    // send text to 3 person.
    err = SendEmail("golang的警报邮件", "xxx@126.com", []string{"xxx@qq.com", "xxx@qq.com", "xxx@126.com"}, MAIL_TEXT, "你猜我能不能把邮件发送出去")
    if err != nil {
        t.Error(err)
        return
    }

    // send html to a person
    err = SendEmail("golang的警报邮件", "xxx@126.com", []string{"xxx@qq.com"}, MAIL_HTML, "<h1>你好啊朋友</h1>")
    if err != nil {
        t.Error(err)
        return
    }
    log.D("TestSendEmail test success")
}