golang 发送邮件
使用 gomail
先下载gomail 包
go get gopkg.in/gomail.v2
代码:
package main import ( "fmt" "gopkg.in/gomail.v2" "log" "strconv" ) const ( SMTPHost = "smtp.qiye.aliyun.com" SMTPPort = "465" //25 SMTPUsername = "xxx@x.com" SMTPPassword = "xxxx" ) func SendMail(mailTo []string, subject string, body string) error { // 设置邮箱主体 mailConn := map[string]string{ "user": SMTPUsername, "pass": SMTPPassword, "host": SMTPHost, "port": SMTPPort, } port, _ := strconv.Atoi(mailConn["port"]) m := gomail.NewMessage() m.SetHeader("From", m.FormatAddress(mailConn["user"], "银众网")) // 添加别名 m.SetHeader("To", mailTo...) // 发送给用户(可以多个) m.SetHeader("Subject", subject) // 设置邮件主题 m.SetBody("text/html", body) // 设置邮件正文 d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["pass"]) // 设置邮件正文 err := d.DialAndSend(m) return err } func main() { // 发送方 mailTo := []string{ "xxx", // 这里最好写成邮箱收发件时的这种标记格式 } // 邮件主题 subject := "Hello" // 邮件正文 body := "Automatic send by Go gomail from xxx官方." err := SendMail(mailTo, subject, body) if err != nil { log.Print(err) fmt.Printf("Send fail!") return } fmt.Println("send successfully!") }