最近看了下go發送smtp郵件,于是總結一下
簡單示例
- 先上一個最簡單的代碼 (網上摟的代碼改了改)
package main
import (
"fmt"
"net/smtp"
)
const (
// 郵件服務器地址
SMTP_MAIL_HOST = "smtp.qq.com"
// 埠
SMTP_MAIL_PORT = "587"
// 發送郵件用戶賬號
SMTP_MAIL_USER = "[email protected]"
// 授權密碼
SMTP_MAIL_PWD = "xxxx"
// 發送郵件昵稱
SMTP_MAIL_NICKNAME = "lewis"
)
func main() {
//宣告err, subject,body型別,并為address,auth以及contentType賦值,
//subeject是主題,body是郵件內容, address是收件人
var err error
var subject, body string
address := "[email protected]"
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格式化為這個格式,直接賦值也行,
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")
}
}
收到郵件截圖

簡要說明
-
const中SMTP_MAIL_PWD 是我申請開通qq郵箱的smtp服務時,騰訊發來的密碼,并不是qq郵箱的密碼,
-
可以看到郵件截圖中顯示(無主題),郵件也沒內容,因為subeject和body我只宣告了,但并未賦值,因此這倆為空,
-
contentType設為text/html,當然也有其他格式,
-
其余的注釋里應該說的比較清楚了
稍加改進
-
我們來加點常用的功能
-
收件人有多個
-
當然還得設定主題和郵件內容
-
發郵件功能單獨封裝為一個函式,然后main里呼叫
-
package main
import (
"fmt"
"net/smtp"
)
const (
// 郵件服務器地址
SMTP_MAIL_HOST = "smtp.qq.com"
// 埠
SMTP_MAIL_PORT = "587"
// 發送郵件用戶賬號
SMTP_MAIL_USER = "[email protected]"
// 授權密碼
SMTP_MAIL_PWD = "xxxx"
// 發送郵件昵稱
SMTP_MAIL_NICKNAME = "lewis"
)
func main() {
address := []string{"[email protected]", "[email protected]"}
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
}
收到郵件截圖


簡要說明
- 收件人是兩個,都收到了
- subject有了
- body使用了br標簽換行,直接在``內化換行試了下不行
- 另外如果發郵件報錯:550 Mailbox not found or access denied,百度會發現是:您要發送的收件人短時間內收到大量郵件,為避免受到惡意攻擊,暫時禁止向該收件人發信,但其實收件人的地址不存在時也會報這個錯誤,
OK,先寫這么多吧,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/116118.html
標籤:Go
