golang实现通过smtp发送电子邮件的方法
时间:2020-12-02 13:04:21|栏目:Golang|点击: 次
本文实例讲述了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 := "mail1@mail.com"
password := "password"
toEmail := "mail2@mail.com"
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)
}
}
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{"发送人", 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语言程序设计有所帮助。
栏 目:Golang
本文地址:http://www.codeinn.net/misctech/28684.html