golang实现通过smtp发送电子邮件的方法
本文实例讲述了golang实现通过smtp发送电子邮件的方法。分享给大家供大家参考,具体如下:
今天写了一个公司的邮件发送后台服务,php只需要把邮件存入数据库,然后golang写的mailservice就会吧邮件发送出去.这个公司的代码就不发出来的,以为带有公司的业务逻辑,我把代码整理了一下发布出来供大家参考.呵呵
代码如下:
package main import ( "fmt" "net/mail" "net/smtp" "encoding/base64" ) func main() { b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") host := "smtp.mail.com" email := "[email protected]" password := "password" toEmail := "[email protected]" from := mail.Address{"发送人", 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("邮件标题2"))) header["MIME-Version"] = "1.0" header["Content-Type"] = "text/html; charset=UTF-8" header["Content-Transfer-Encoding"] = "base64" body := "我是一封电子邮件!golang发出."; 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) } }
希望本文所述对大家Go语言程序设计有所帮助。
相关推荐
zhangwentaohh 2020-09-16
文山羊 2020-08-16
行吟阁 2020-07-04
xiaodaiwang 2020-06-12
JasonYeung 2020-06-07
oXiaoChong 2020-06-01
sunnyhappy0 2020-05-19
airfling 2020-05-19
singer 2020-05-06
winmeanyoung 2020-04-11
wenjs00 2020-03-06
vs00ASPNET 2020-02-19
zhangpan 2020-01-10
ITxiaobaibai 2020-01-03
huakai 2019-12-29
cbao 2019-12-24
idning 2019-12-21