###go语言自带smtp的使用,本文主要对qq发送邮件的使用,部分代码参考。
* user:登陆邮箱账号
* password:不是qq邮箱密码,需要登陆你的qq邮箱,在设置,账号,启用IMAP/SMTP服务,会发送一段身份验证符号给你,用这个登陆
* host:smtp.qq.com:587
* to:加入多个邮箱,已逗号隔开,相当于群发。
* subject:发送的主题
* body:发送的内容
* mailtyoe: 发送的内容是文本还是html
```javascript
package main
import (
"fmt"
"net/smtp"
"strings"
)
func SendMail(user, password, host, to, subject, body, mailtype string) error {
hp := strings.Split(host, ":")
auth := smtp.PlainAuth(password, user, password, hp[0])
var content_type string
if mailtype == "html" {
content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
} else {
content_type = "Content-Type: text/plain" + "; charset=UTF-8"
}
msg := []byte("To: " + to + "\r\nFrom: " + user + "<" + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
send_to := strings.Split(to, ";")
err := smtp.SendMail(host, auth, user, send_to, msg)
return err
}
func main() {
user := "********@qq.com"
password := "**********"
host := "smtp.qq.com:587"
to := "*********@qq.com;*******@qq.com"
subject := "Test send email by golang"
body := `
<html>
<body>
<h3>
"Test send email by golang"
</h3>
</body>
</html>
`
fmt.Println("send email")
err := SendMail(user, password, host, to, subject, body, "html")
if err != nil {
fmt.Println("send mail error!")
fmt.Println(err)
} else {
fmt.Println("send mail success!")
}
}
```
有疑问加站长微信联系(非本文作者)