最近在学习Golang、顺便在写爬虫的过程中需要把爬取出来的结果通过邮件发送到指定邮箱里面保存; 所以需要用到Golang里面的smtp模块;
但是从Go官方的smtp介绍中直接使用官方的测试代码虽然能发送邮件、但是不能设置邮件主题甚至连邮件内容都不能设置;
所以借鉴了网上的一些经验和Go官方的smtp测试代码之后完成能够发送邮件主题和邮件内容;
import (
"fmt"
"net/smtp"
"strings"
)
func SendToMail(user, password, host, to, subject, body, mailtype string) error {
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", 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 + "rnFrom: " + user + "<" + user +
">rnSubject: " + subject + "rn" + content_type + "rnrn" + body)
send_to := strings.Split(to, ";")
err := smtp.SendMail(host, auth, user, send_to, msg)
return err
}
func main() {
user := "huaisha1224@126.com"
password := "********"
host := "smtp.126.com:25"
to := "279478776@qq.com"
subject := "使用Golang发送邮件"
body := `
<html>
<body>
<h3>
"Test send to email"
</h3>
</body>
</html>
`
fmt.Println("send email")
err := SendToMail(user, password, host, to, subject, body, "html")
if err != nil {
fmt.Println("Send mail error!")
fmt.Println(err)
} else {
fmt.Println("Send mail success!")
}
}
cmd下切换到代码目录下;运行go run smtp.go即可发送邮件了