发送邮件可以用smtp,也可以用gomail,下面是代码
1、SMTP
package main
import (
"fmt"
"net/smtp"
)
func main() {
mailConn := map[string]string{
"user": "it@go.com",
"pass": "password",
"host": "smtp.go.com",
"port": "25",
}
mailTo:="***@gmail.com"
auth := smtp.PlainAuth("", mailConn["user"], mailConn["pass"], mailConn["host"])
err := smtp.SendMail(mailConn["host"]+":" + mailConn["port"], auth, mailConn["user"], mailTo, []byte( "Done"))
if err != nil {
fmt.Println(err.Error())
}
}
2、gomail
func SendMail(mailTo []string, subject string, body string) error {
mailConn := map[string]string{
"user": "it@go.com",
"pass": "password",
"host": "smtp.go.com",
"port": "25",
}
port, _ := strconv.Atoi(mailConn["port"]) //转换端口类型为int
m := gomail.NewMessage()
m.SetHeader("From", mailConn["user"]) //这种方式可以添加别名,即“XD Game”, 也可以直接用<code>m.SetHeader("From",mailConn["user"])</code> 读者可以自行实验下效果
m.SetHeader("To", mailTo...) //发送给多个用户
m.SetHeader("Subject", subject) //设置邮件主题
m.SetBody("text/html", body) //设置邮件正文
d := gomail.Dialer{
Host: mailConn["host"],
Port: port,
Username: mailConn["user"],
Password: mailConn["pass"],
SSL: false,
}
//d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
err := d.DialAndSend(m)
if err != nil {
fmt.Println(err.Error())
}
return err
}
有疑问加站长微信联系(非本文作者)