`
DarkWingBoy
  • 浏览: 50269 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

golang通过smtp发送电子邮件

 
阅读更多

http://www.dotcoo.com/golang-smtp-mail

今天写了一个公司的邮件发送后台服务,php只需要把邮件存入数据库,然后golang写的mailservice就会吧邮件发送出去.这个公司的代码就不发出来的,以为带有公司的业务逻辑,我把代码整理了一下发布出来供大家参考.呵呵

package main
   
import (
    "fmt"
    "net/mail"
    "net/smtp"
    "encoding/base64"
)
   
func main() {
    b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
   
    host := "smtp.mail.com"
    email := "mail1@mail.com"
    password := "password"
    toEmail := "mail2@mail.com"
   
    from := mail.Address{"发送人", email}
    to := mail.Address{"接收人", toEmail}
   
    header := make(map[string]string)
    header["From"] = from.String()
    header["To"] = to.String()
    header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte("邮件标题2")))
    header["MIME-Version"] = "1.0"
    header["Content-Type"] = "text/html; charset=UTF-8"
    header["Content-Transfer-Encoding"] = "base64"
   
    body := "我是一封电子邮件!golang发出.";
   
    message := ""
    for k, v := range header {
        message += fmt.Sprintf("%s: %s\r\n", k, v)
    }
    message += "\r\n" + b64.EncodeToString([]byte(body))
   
    auth := smtp.PlainAuth(
        "",
        email,
        password,
        host,
    )
   
    err := smtp.SendMail(
        host+":25",
        auth,
        email,
        []string{to.Address},
        []byte(message),
    )
    if err != nil {
        panic(err)
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics