使用 smtp.SendMail() 傳送電子郵件
在 Go 中傳送電子郵件非常簡單。它有助於理解 RFC 822,它指定了電子郵件需要的樣式,下面的程式碼傳送符合 RFC 822 的電子郵件。
package main
import (
"fmt"
"net/smtp"
)
func main() {
// user we are authorizing as
from := "someuser@example.com"
// use we are sending email to
to := "otheruser@example.com"
// server we are authorized to send email through
host := "mail.example.com"
// Create the authentication for the SendMail()
// using PlainText, but other authentication methods are encouraged
auth := smtp.PlainAuth("", from, "password", host)
// NOTE: Using the backtick here ` works like a heredoc, which is why all the
// rest of the lines are forced to the beginning of the line, otherwise the
// formatting is wrong for the RFC 822 style
message := `To: "Some User" <someuser@example.com>
From: "Other User" <otheruser@example.com>
Subject: Testing Email From Go!!
This is the message we are sending. That's it!
`
if err := smtp.SendMail(host+":25", auth, from, []string{to}, []byte(message)); err != nil {
fmt.Println("Error SendMail: ", err)
os.Exit(1)
}
fmt.Println("Email Sent!")
}
以上將傳送如下訊息:
To: "Other User" <otheruser@example.com>
From: "Some User" <someuser@example.com>
Subject: Testing Email From Go!!
This is the message we are sending. That's it!
.