// SendMail connects to the server at addr, switches to TLS if
// possible, authenticates with the optional mechanism a if possible,
// and then sends an email from address from, to addresses to, with
// message msg.
// The addr must include a port, as in "mail.example.com:smtp".
//
// The addresses in the to parameter are the SMTP RCPT addresses.
//
// The msg parameter should be an RFC 822-style email with headers
// first, a blank line, and then the message body. The lines of msg
// should be CRLF terminated. The msg headers should usually include
// fields such as "From", "To", "Subject", and "Cc". Sending "Bcc"
// messages is accomplished by including an email address in the to
// parameter but not including it in the msg headers.
//
// The SendMail function and the net/smtp package are low-level
// mechanisms and provide no support for DKIM signing, MIME
// attachments (see the mime/multipart package), or other mail
// functionality. Higher-level packages exist outside of the standard
// library.
函數原型
func SendMail(addr string, a Auth, from string, to []string, msg []byte) error
/*!
username 發送者郵件
password 授權碼
host 主機地址 smtp.qq.com:587 或 smtp.qq.com:25
to 接收郵箱 多個接收郵箱使用 ; 隔開
name 發送人名稱
subject 發送主題
body 發送內容
mailType 發送郵件內容類型
*/
func SendMail(username, password, host, to, name,subject, body, mailType string) error {
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", username, password,hp[0])
var contentType string
if mailType == "html" {
contentType = "Content-Type: text/" + mailType + "; charset=UTF-8"
} else {
contentType = "Content-Type: text/plain" + "; charset=UTF-8"
}
msg := []byte("To: " + to + "\r\nFrom: " + name + "<" + username + ">\r\nSubject: " + subject + "\r\n" + contentType + "\r\n\r\n" + body)
sendTo := strings.Split(to, ";")
err := smtp.SendMail(host, auth, username, sendTo, msg)
return err
}
func main() {
err := SendMail(
"zer******0115@foxmail.com",
"kcll******hjbbih",
"smtp.qq.com:587",
"**********@qq.com",
"學海無涯",
"測試",
"這是一封測試郵件",
"html",
)
if err != nil{
log.Fatal(err)
}
}