發(fā)送郵件可以用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"]) //轉(zhuǎn)換端口類型為int
m := gomail.NewMessage()
m.SetHeader("From", mailConn["user"]) //這種方式可以添加別名饮怯,即“XD Game”, 也可以直接用<code>m.SetHeader("From",mailConn["user"])</code> 讀者可以自行實(shí)驗(yàn)下效果
m.SetHeader("To", mailTo...) //發(fā)送給多個(gè)用戶
m.SetHeader("Subject", subject) //設(shè)置郵件主題
m.SetBody("text/html", body) //設(shè)置郵件正文
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
}