全部产品
邮件推送

SMTP 之 Go 调用示例

更新时间:2017-08-09 15:22:39   分享:   

使用 Go 语言通过 SMTP 发送邮件

  1. package main
  2. import (
  3. "fmt"
  4. "net/smtp"
  5. "strings"
  6. )
  7. func SendToMail(user, password, host, to, subject, body, mailtype string) error {
  8. hp := strings.Split(host, ":")
  9. auth := smtp.PlainAuth("", user, password, hp[0])
  10. var content_type string
  11. if mailtype == "html" {
  12. content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
  13. } else {
  14. content_type = "Content-Type: text/plain" + "; charset=UTF-8"
  15. }
  16. msg := []byte("To: " + to + "\r\nFrom: " + user + "\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
  17. send_to := strings.Split(to, ";")
  18. err := smtp.SendMail(host, auth, user, send_to, msg)
  19. return err
  20. }
  21. func main() {
  22. user := "控制台创建的发信地址"
  23. password := "控制台设置的SMTP密码"
  24. host := "smtpdm.aliyun.com:25"
  25. to := "目标地址"
  26. subject := "test Golang to sendmail"
  27. body := `
  28. <html>
  29. <body>
  30. <h3>
  31. "Test send to email"
  32. </h3>
  33. </body>
  34. </html>
  35. `
  36. fmt.Println("send email")
  37. err := SendToMail(user, password, host, to, subject, body, "html")
  38. if err != nil {
  39. fmt.Println("Send mail error!")
  40. fmt.Println(err)
  41. } else {
  42. fmt.Println("Send mail success!")
  43. }
  44. }
本文导读目录
本文导读目录
以上内容是否对您有帮助?