SMTP using net/mail with STARTTLS
golang    2016-05-28 15:19:05    403    0    0
jim   golang

1. Mail Configuration

When we have certificates for our SMTP servers, the TLSSkipVerify should be set to true. Otherwise, set to false

  1. // MailConfig contains all configuration for mail
  2. type MailConfig struct {
  3. AuthMailAddr string
  4. AuthPassword string
  5. SendFrom string
  6. SMTPHost string
  7. TLSSkipVerify bool
  8. }
  9. var config MailConfig
  10. func SendMail(mailto string, subject string, body string) error {
  11. // Code
  12. }

2. Set From and To

  1. from := mail.Address{
  2. Name: "",
  3. Address: config.SendFrom,
  4. }
  5. to := mail.Address{
  6. Name: "",
  7. Address: mailto,
  8. }

3. Setup Header and Message

  1. // Setup headers
  2. headers := make(map[string]string)
  3. headers["From"] = from.String()
  4. headers["To"] = to.String()
  5. headers["Subject"] = subject
  6. // Setup message
  7. message := ""
  8. for k, v := range headers {
  9. message += fmt.Sprintf("%s: %s\r\n", k, v)
  10. }
  11. message += "\r\n" + body

4. Start Connection

  1. // Connect to the SMTP Server
  2. host, _, _ := net.SplitHostPort(config.SMTPHost)
  3. auth := smtp.PlainAuth("", config.AuthMailAddr, config.AuthPassword, host)
  4. // TLS config
  5. tlsconfig := &tls.Config{
  6. InsecureSkipVerify: config.TLSSkipVerify,
  7. ServerName: host,
  8. }
  9. c, err := smtp.Dial(config.SMTPHost)
  10. if err != nil {
  11. log.Panic(err)
  12. }
  13. c.StartTLS(tlsconfig)

5. Auth and Send Data

  1. // Auth
  2. if err = c.Auth(auth); err != nil {
  3. return err
  4. }
  5. // To && From
  6. if err = c.Mail(from.Address); err != nil {
  7. return err
  8. }
  9. if err = c.Rcpt(to.Address); err != nil {
  10. return err
  11. }
  12. // Data
  13. w, err := c.Data()
  14. if err != nil {
  15. return err
  16. }
  17. _, err = w.Write([]byte(message))
  18. if err != nil {
  19. return err
  20. }
  21. err = w.Close()
  22. if err != nil {
  23. return err
  24. }
  25. c.Quit()

Pre: How to Import Virtual Machine Image into AWS

Next: No Post

403
Table of content