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郵件內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!