本文最后更新于 2024年4月10日 晚上
配置 SMTP 服务 发送邮件时需要与邮箱服务提供商的 SMTP 服务器通信,将邮件标题、内容、收件人地址等信息发送到 SMTP 服务器。随后,SMTP 服务器将该封邮件投递到收件人地址所有的 SMTP 服务器。收件人才能看到该封邮件。
配置 SMTP 服务以 QQ 邮箱为例。
登录 QQ 邮箱后,电点击左上方名字下的 “设置”,选择 “账户” 栏,下拉到 “POP3、IMAP…服务” 位置,选择开启 “POP3/SMTP 服务”。
开启 SMTP 服务后点击下方蓝色的 “生成授权码”,使用手机发送指定的短信后,获取到授权码,保存该授权码,发送邮件时需要。
官方库 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 var ( fromUser = "xx@qq.com" password = "xxx" toUser = []string {"xx@163.com" } smtpServiceAddr = "smtp.qq.com" smtpServicePort = 587 msg = fmt.Sprintf( "To: %s\r\nSubject: %s\r\n\r\n%s\r\n" , toUser, "hello world" , "This is the email body." , ) auth = smtp.PlainAuth("" , fromUser, password, smtpServiceAddr) )func main () { err := smtp.SendMail( fmt.Sprintf("%s:%d" , smtpServiceAddr, smtpServicePort), auth, fmt.Sprintf("xx <%s>" , fromUser), toUser, []byte (msg), ) if err != nil { log.Fatalf("Send email error: %s." , err) } log.Println("Send email success." ) }
第三方库 email
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 func main () { e := email.NewEmail() e.From = "xx <xx@qq.com>" e.To = toUser e.Subject = "hello world" e.Text = []byte ("This is the email body." ) e.HTML = []byte ("<span style=\"color: red;\">This is the email body.</span>" ) e.AttachFile("test.xlsx" ) e.Cc = []string {"xx@126.com" } e.Bcc = []string {"xx@aliyun.com" } err := e.Send( fmt.Sprintf("%s:%d" , smtpServiceAddr, smtpServicePort), auth, ) if err != nil { log.Fatalf("Send email error: %s." , err) } log.Println("Send email success." ) }