海运的博客

golang通过qq mail smtp ssl发送邮件

发布时间:April 15, 2018 // 分类: // No Comments

转自:https://www.oschina.net/code/snippet_166520_34694

package main
 
import (
    "crypto/tls"
    "fmt"
    "log"
    "net"
    "net/smtp"
)
 
func main() {
    host := "smtp.qq.com"
    port := 465
    email := "xxx@qq.com"
    password := "xxx"
    toEmail := "xxx@qq.com"
 
    header := make(map[string]string)
    header["From"] = "test" + "<" + email + ">"
    header["To"] = toEmail
    header["Subject"] = "邮件标题"
    header["Content-Type"] = "text/html; charset=UTF-8"
 
    body := "我是一封电子邮件!golang发出."
 
    message := ""
    for k, v := range header {
        message += fmt.Sprintf("%s: %s\r\n", k, v)
    }
    message += "\r\n" + body
 
    auth := smtp.PlainAuth(
        "",
        email,
        password,
        host,
    )
 
    err := SendMailUsingTLS(
        fmt.Sprintf("%s:%d", host, port),
        auth,
        email,
        []string{toEmail},
        []byte(message),
    )
 
    if err != nil {
        panic(err)
    }
}
 
//return a smtp client
func Dial(addr string) (*smtp.Client, error) {
    conn, err := tls.Dial("tcp", addr, nil)
    if err != nil {
        log.Println("Dialing Error:", err)
        return nil, err
    }
    //分解主机端口字符串
    host, _, _ := net.SplitHostPort(addr)
    return smtp.NewClient(conn, host)
}
 
//参考net/smtp的func SendMail()
//使用net.Dial连接tls(ssl)端口时,smtp.NewClient()会卡住且不提示err
//len(to)>1时,to[1]开始提示是密送
func SendMailUsingTLS(addr string, auth smtp.Auth, from string,
    to []string, msg []byte) (err error) {
 
    //create smtp client
    c, err := Dial(addr)
    if err != nil {
        log.Println("Create smpt client error:", err)
        return err
    }
    defer c.Close()
 
    if auth != nil {
        if ok, _ := c.Extension("AUTH"); ok {
            if err = c.Auth(auth); err != nil {
                log.Println("Error during AUTH", err)
                return err
            }
        }
    }
 
    if err = c.Mail(from); err != nil {
        return err
    }
 
    for _, addr := range to {
        if err = c.Rcpt(addr); err != nil {
            return err
        }
    }
 
    w, err := c.Data()
    if err != nil {
        return err
    }
 
    _, err = w.Write(msg)
    if err != nil {
        return err
    }
 
    err = w.Close()
    if err != nil {
        return err
    }
 
    return c.Quit()
}

标签:none

发表评论

分类
最新文章
最近回复
  • 404NTF: 交叉编译的作用是?
  • 404NTF: 请教一下 CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go ...
  • 小智: 安利个PHP开发以太坊区块链的教程: http://xc.hubwiz.com/course/...
  • 陈浩南: 您好,您教程中的 dev.openwrt.org.cn 现在似乎不可用了。请问现在应该在哪里下...
  • 斑马斑马: 怎么查看虚拟机CPU 内存使用情况
  • zzg: http://downloads.openwrt.org.cn/PandoraBox/rali...
  • xiongrui: 看图
  • 傻狍子: filebrowser好像和这功能一样? https://github.com/filebro...
  • 陶国文: 想看看能不能安装
  • 傻狍子: 服务端设置了用户名密码认证的话,在openwrt的openvpn客户端的配置文件当中该如何更改...
页面执行耗时:0.035秒。-->