edit-icon download-icon

SMTP-Go

Last Updated: Sep 03, 2018

The following example shows how to send an email through SMTP using the Go language(Version 1.9).

  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 := "The mail address created in the console"
  23. password := "The SMTP password set in the console"
  24. host := "smtpdm.aliyun.com:25"
  25. to := "Destination address"
  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. }

If your Go language Version is 1.9.2, errors such as “unencrypted connection” may come about. This version demands LoginAuth with encrytion and here is the addition:

  1. type loginAuth struct {
  2. username, password string
  3. }
  4. func LoginAuth(username, password string) smtp.Auth {
  5. return &loginAuth{username, password}
  6. }
  7. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  8. // return "LOGIN", []byte{}, nil
  9. return "LOGIN", []byte(a.username), nil
  10. }
  11. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  12. if more {
  13. switch string(fromServer) {
  14. case "Username:":
  15. return []byte(a.username), nil
  16. case "Password:":
  17. return []byte(a.password), nil
  18. }
  19. }
  20. return nil, nil
  21. }

Then change auth method to the following:

  1. auth := LoginAuth(user, password)
Thank you! We've received your feedback.