最近看了下go發送smtp郵件,因而總結一下html
package main import ( "fmt" "net/smtp" ) const ( // 郵件服務器地址 SMTP_MAIL_HOST = "smtp.qq.com" // 端口 SMTP_MAIL_PORT = "587" // 發送郵件用戶帳號 SMTP_MAIL_USER = "1348581672@qq.com" // 受權密碼 SMTP_MAIL_PWD = "xxxx" // 發送郵件暱稱 SMTP_MAIL_NICKNAME = "lewis" ) func main() { //聲明err, subject,body類型,併爲address,auth以及contentType賦值, //subject是主題,body是郵件內容, address是收件人 var err error var subject, body string address := "lewissunp@outlook.com" auth := smtp.PlainAuth("", SMTP_MAIL_USER, SMTP_MAIL_PWD, SMTP_MAIL_HOST) contentType := "Content-Type: text/html; charset=UTF-8" //要發送的消息,能夠直接寫在[]bytes裏,可是看着太亂,所以使用格式化 s := fmt.Sprintf("To:%s\r\nFrom:%s<%s>\r\nSubject:%s\r\n%s\r\n\r\n%s", address, SMTP_MAIL_NICKNAME, SMTP_MAIL_USER, subject, contentType, body) msg := []byte(s) //郵件服務地址格式是"host:port"。 addr := fmt.Sprintf("%s:%s", SMTP_MAIL_HOST, SMTP_MAIL_PORT) //發送郵件 err = smtp.SendMail(addr, auth, SMTP_MAIL_USER, []string{address}, msg) if err != nil { fmt.Println(err) } else { fmt.Println("send email succeed") } }
收到郵件截圖
shell
簡要說明服務器
const中SMTP_MAIL_PWD 是我申請開通qq郵箱的smtp服務時,騰訊發來的密碼,並非qq郵箱的密碼。函數
能夠看到郵件截圖中顯示(無主題),郵件也沒內容,由於subeject和body我只聲明瞭,但並未賦值,所以這倆爲空。this
contentType設爲text/html,固然也有其餘格式。code
其他的註釋裏應該說的比較清楚了htm
咱們來加點經常使用的功能blog
收件人有多個string
固然還得設置主題和郵件內容it
發郵件功能單獨封裝爲一個函數,而後main裏調用
package main import ( "fmt" "net/smtp" ) const ( // 郵件服務器地址 SMTP_MAIL_HOST = "smtp.qq.com" // 端口 SMTP_MAIL_PORT = "587" // 發送郵件用戶帳號 SMTP_MAIL_USER = "1348581672@qq.com" // 受權密碼 SMTP_MAIL_PWD = "xxxx" // 發送郵件暱稱 SMTP_MAIL_NICKNAME = "lewis" ) func main() { address := []string{"norton_s@qq.com", "lewissunp@outlook.com"} subject := "test mail" body := `<br>hello!</br> <br>this is a test email, pls ignore it.</br>` SendMail(address, subject, body) } func SendMail(address []string, subject, body string) (err error) { // 認證, content-type設置 auth := smtp.PlainAuth("", SMTP_MAIL_USER, SMTP_MAIL_PWD, SMTP_MAIL_HOST) contentType := "Content-Type: text/html; charset=UTF-8" // 由於收件人,即address有多個,因此須要遍歷,挨個發送 for _, to := range address { s := fmt.Sprintf("To:%s\r\nFrom:%s<%s>\r\nSubject:%s\r\n%s\r\n\r\n%s", to, SMTP_MAIL_NICKNAME, SMTP_MAIL_USER, subject, contentType, body) msg := []byte(s) addr := fmt.Sprintf("%s:%s", SMTP_MAIL_HOST, SMTP_MAIL_PORT) err = smtp.SendMail(addr, auth, SMTP_MAIL_USER, []string{to}, msg) if err != nil { return err } } return err }
收到郵件截圖
簡要說明
OK,先到這裏,後面找時間繼續更新。