package main
import (
"crypto/tls"
"fmt"
"net/smtp"
"strings"
)
const (
EMAIL_FORM = "[email protected]"
EMAIL_FORM_PW = "emailpassword"
EMAIL_FORM_HOST = "smtp.sina.com"
)
func SendToMail(host string, port uint, //port = 25 (SMTP)
from, password, toList string,
subject, body, mailtype string) error {
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", from, password, host)
content_type := "text/plain" + "; charset=UTF-8"
if mailtype == "html" {
content_type = "text/" + mailtype + "; charset=UTF-8"
}
msg := fmt.Sprintf("To: %s\n", toList)
msg += fmt.Sprintf("From: %s\n", from)
msg += fmt.Sprintf("Subject: %s\n", subject)
msg += fmt.Sprintf("Content-Type: %s\n", content_type)
msg += fmt.Sprintf("%s\n", body)
send_to := strings.Split(toList, ";")
serverAddr := fmt.Sprintf("%s:%d", host, port)
err := smtp.SendMail(serverAddr, auth, from, send_to, []byte(msg))
return err
}
func SendMailSSL(host string, port uint, //port = 465 (SMTP OVER SSL)
from, password, toList string,
subject, body, mailtype string) (err error) {
auth := smtp.PlainAuth("", from, password, host)
content_type := "text/plain" + "; charset=UTF-8"
if mailtype == "html" {
content_type = "text/" + mailtype + "; charset=UTF-8"
}
msg := fmt.Sprintf("To: %s\n", toList)
msg += fmt.Sprintf("From: %s\n", from)
msg += fmt.Sprintf("Subject: %s\n", subject)
msg += fmt.Sprintf("Content-Type: %s\n", content_type)
msg += fmt.Sprintf("%s\n", body)
send_to := strings.Split(toList, ";")
serverAddr := fmt.Sprintf("%s:%d", host, port)
conn, err := tls.Dial("tcp", serverAddr, nil)
if err != nil {
fmt.Printf("tls.Dial err=%v\n", err)
return err
}
c, err := smtp.NewClient(conn, host)
if err != nil {
fmt.Printf("Error SMTP connection err=%v\n", err)
return err
}
if auth != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(auth); err != nil {
fmt.Printf("Error during AUTH err=%v\n", err)
return err
}
}
}
if err = c.Mail(from); err != nil {
return err
}
for _, addr := range send_to {
if err = c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write([]byte(msg))
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
}
func main() {
to := "[email protected]"
subject := "Golang email3"
body := `
<html>
<body>
<h3>
"Test send to email"
</h3>
</body>
</html>
`
fmt.Println("send email")
err := SendMailSSL(EMAIL_FORM_HOST, 25,
EMAIL_FORM, EMAIL_FORM_PW, to,
subject, body, "html")
if err != nil {
fmt.Println("Send mail error!")
fmt.Println(err)
} else {
fmt.Println("Send mail success!")
}
}
注:
msg的格式必須嚴格保持如下樣式,否則會失敗:
To: [email protected]
From: [email protected]
Subject: Golang email
Content-Type: mailcontent