直接回答:Go 标准库的 net/smtp 就能发邮件:用 PlainAuth 做认证,注意邮箱这里要填授权码而不是登录密码,中文主题还需要按 RFC 2047 编码,否则会变乱码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package main
import ( "fmt" "net/smtp" )
func main() { smtpHost := "smtp.qq.com" smtpUsername := "example@example.com" smtpPassword := "这里是密码" from := "example@example.com" to := "example@example.com" subject := "测试邮件" body := "这是一封测试邮件的内容" auth := smtp.PlainAuth("", smtpUsername, smtpPassword, smtpHost) headers := make(map[string]string) headers["From"] = from headers["To"] = to headers["Subject"] = subject message := "" for k, v := range headers { message += fmt.Sprintf("%s: %s\r\n", k, v) } message += "\r\n" + body err := smtp.SendMail(smtpHost+":587", auth, from, []string{to}, []byte(message)) if err != nil { fmt.Println(err.Error()) return } }
|
这篇笔记整理自我自己的实践记录,如果做法有出入,或者你踩过别的坑,欢迎到留言板一起聊聊。