golang实现通过smtp发送电子邮件的方法
程序员文章站
2022-07-05 08:51:39
本文实例讲述了golang实现通过smtp发送电子邮件的方法。分享给大家供大家参考,具体如下:
今天写了一个公司的邮件发送后台服务,php只需要把邮件存入数据库,然后go...
本文实例讲述了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语言程序设计有所帮助。