本文實(shí)例講述了golang實(shí)現(xiàn)通過(guò)smtp發(fā)送電子郵件的方法。分享給大家供大家參考,具體如下:
今天寫(xiě)了一個(gè)公司的郵件發(fā)送后臺(tái)服務(wù),php只需要把郵件存入數(shù)據(jù)庫(kù),然后golang寫(xiě)的mailservice就會(huì)吧郵件發(fā)送出去.這個(gè)公司的代碼就不發(fā)出來(lái)的,以為帶有公司的業(yè)務(wù)邏輯,我把代碼整理了一下發(fā)布出來(lái)供大家參考.呵呵
復(fù)制代碼 代碼如下:
package main
import (
"fmt"
"net/mail"
"net/smtp"
"encoding/base64"
)
func main() {
b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
host := "smtp.mail.com"
email := "mail1@mail.com"
password := "password"
toEmail := "mail2@mail.com"
from := mail.Address{"發(fā)送人", email}
to := mail.Address{"接收人", toEmail}
header := make(map[string]string)
header["From"] = from.String()
header["To"] = to.String()
header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte("郵件標(biāo)題2")))
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/html; charset=UTF-8"
header["Content-Transfer-Encoding"] = "base64"
body := "我是一封電子郵件!golang發(fā)出.";
message := ""
for k, v := range header {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + b64.EncodeToString([]byte(body))
auth := smtp.PlainAuth(
"",
email,
password,
host,
)
err := smtp.SendMail(
host+":25",
auth,
email,
[]string{to.Address},
[]byte(message),
)
if err != nil {
panic(err)
}
}
希望本文所述對(duì)大家Go語(yǔ)言程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Go語(yǔ)言通過(guò)smtp發(fā)送郵件的方法
- go語(yǔ)言發(fā)送smtp郵件的實(shí)現(xiàn)示例