package main
import (
"fmt"
"net/smtp"
)
const (
// 邮件服务器地址
SMTP_MAIL_HOST = "smtp.qq.com"
// 端口
SMTP_MAIL_PORT = "587"
// 发送邮件用户账号
SMTP_MAIL_USER = "1348581672@qq.com"
// 授权密码
SMTP_MAIL_PWD = "xxxx"
// 发送邮件昵称
SMTP_MAIL_NICKNAME = "lewis"
)
func main() {
//声明err, subject,body类型,并为address,auth以及contentType赋值,
//subeject是主题,body是邮件内容, address是收件人
var err error
var subject, body string
address := "lewissunp@outlook.com"
auth := smtp.PlainAuth("", SMTP_MAIL_USER, SMTP_MAIL_PWD, SMTP_MAIL_HOST)
contentType := "Content-Type: text/html; charset=UTF-8"
//要发送的消息,可以直接写在[]bytes里,但是看着太乱,因此使用格式化
s := fmt.Sprintf("To:%s\r\nFrom:%s%s>\r\nSubject:%s\r\n%s\r\n\r\n%s",
address, SMTP_MAIL_NICKNAME, SMTP_MAIL_USER, subject, contentType, body)
msg := []byte(s)
//邮件服务地址格式是"host:port",因此把addr格式化为这个格式,直接赋值也行。
addr := fmt.Sprintf("%s:%s", SMTP_MAIL_HOST, SMTP_MAIL_PORT)
//发送邮件
err = smtp.SendMail(addr, auth, SMTP_MAIL_USER, []string{address}, msg)
if err != nil {
fmt.Println(err)
} else {
fmt.Println("send email succeed")
}
}
package main
import (
"fmt"
"net/smtp"
)
const (
// 邮件服务器地址
SMTP_MAIL_HOST = "smtp.qq.com"
// 端口
SMTP_MAIL_PORT = "587"
// 发送邮件用户账号
SMTP_MAIL_USER = "1348581672@qq.com"
// 授权密码
SMTP_MAIL_PWD = "jhguvicvhrnwgaeh"
// 发送邮件昵称
SMTP_MAIL_NICKNAME = "lewis"
)
func main() {
address := []string{"norton_s@qq.com", "lewissunp@outlook.com"}
subject := "test mail"
body :=
`br>hello!/br>
br>this is a test email, pls ignore it./br>`
SendMail(address, subject, body)
}
func SendMail(address []string, subject, body string) (err error) {
// 认证, content-type设置
auth := smtp.PlainAuth("", SMTP_MAIL_USER, SMTP_MAIL_PWD, SMTP_MAIL_HOST)
contentType := "Content-Type: text/html; charset=UTF-8"
// 因为收件人,即address有多个,所以需要遍历,挨个发送
for _, to := range address {
s := fmt.Sprintf("To:%s\r\nFrom:%s%s>\r\nSubject:%s\r\n%s\r\n\r\n%s", to, SMTP_MAIL_NICKNAME, SMTP_MAIL_USER, subject, contentType, body)
msg := []byte(s)
addr := fmt.Sprintf("%s:%s", SMTP_MAIL_HOST, SMTP_MAIL_PORT)
err = smtp.SendMail(addr, auth, SMTP_MAIL_USER, []string{to}, msg)
if err != nil {
return err
}
}
return err
}
到此这篇关于go发送smtp邮件的实现示例的文章就介绍到这了,更多相关go发送smtp邮件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!