你們好我是平也,今天跟你們介紹一款用來發送郵件的Go語言庫email,目前星星1.3k,很是好用。git
初始化項目github
go get github.com/jordan-wright/email複製代碼
本示例項目結構golang
.
├── go.mod
├── go.sum
└── main.go複製代碼
開啓郵箱SMTP服務,以163郵箱爲例,須要先登陸到郵箱後臺點擊開啓按鈕,在發送完短信以後,會獲取到一個受權碼,將受權碼保存,後面須要用到。shell
首先配置好郵件內容服務器
e := email.NewEmail()
e.From = "平也<pingyeaa@163.com>"
e.To = []string{"602588122@qq.com"}
e.Subject = "發現驚天大祕密!"
e.Text = []byte("平也好帥好有智慧哦~")複製代碼
調用Send方法發送郵件,第一個參數是你的發件人郵箱的SMTP域名+端口號,第二個參數用於身份認證ide
e.Send("smtp.163.com:25", smtp.PlainAuth("", "pingyeaa@163.com", "<你的密碼>", "smtp.163.com"))複製代碼
smtp.PlainAuth性能
完整代碼以下spa
package main
import (
"net/smtp"
"github.com/jordan-wright/email"
)
func main() {
e := email.NewEmail()
//e.From = "pingyeaa@163.com"
e.From = "平也 <pingyeaa@163.com>"
e.To = []string{"xxxxxx@qq.com"}
e.Subject = "發現驚天大祕密!"
e.Text = []byte("平也好帥好有智慧哦~")
err := e.Send("smtp.163.com:25", smtp.PlainAuth("", "pingyeaa@163.com", "KQHQCZSXQWPDZYRF", "smtp.163.com"))
if err != nil {
panic(err)
}
}複製代碼
CC全稱是Carbon Copy,意爲抄送,BCC全稱Blind Carbon Copy,意爲暗抄送,收件人看不到被暗抄送給了誰。code
e := email.NewEmail()
e.Cc = []string{"xxxxxxx@qq.com"}
e.Bcc = []string{"xxxxxxx@qq.com"}複製代碼
能夠實例化的時候直接賦值cdn
e := &email.Email{
From: "平也 <pingyeaa@163.com>",
To: []string{"xxxxxxx@qq.com"},
Subject: "發現驚天大祕密!",
Text: []byte("平也好帥好有智慧哦~"),
}複製代碼
發送附件很是簡單,直接傳入文件名便可
e.AttachFile("attachment.txt")複製代碼
也能夠調用Attach自行實現附件發送,AttachFile其實就是對Attach的封裝
func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
f, err := os.Open(filename)
if err != nil {
return
}
defer f.Close()
ct := mime.TypeByExtension(filepath.Ext(filename))
basename := filepath.Base(filename)
return e.Attach(f, basename, ct)
}複製代碼
因爲頻繁發送郵件會不斷的與SMTP服務器創建鏈接,比較影響性能,因此email提供了鏈接池的功能
auth := smtp.PlainAuth("", "pingyeaa@163.com", "<你的密碼>", "smtp.163.com")
p, _ := email.NewPool("smtp.163.com:25", 4, auth)複製代碼
建立成功後,就能夠藉助鏈接池來發送郵件
e := email.NewEmail()
e.From = "平也 <pingyeaa@163.com>"
e.To = []string{"xxxxxx@qq.com"}
e.Subject = "發現驚天大祕密!"
e.Text = []byte("平也好帥好有智慧哦~")
p.Send(e, 10*time.Second)複製代碼
Go語言庫代碼示例,歡迎star github.com/pingyeaa/go…
感謝你們的觀看,若是以爲文章對你有所幫助,歡迎關注公衆號「平也」,聚焦Go語言與技術原理。