Jim's Blog
Toggle navigation
Jim's Blog
Home
About Me
Archives
Tags
SMTP using net/mail with STARTTLS
golang
2016-05-28 15:19:05
361
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 ``` golang // MailConfig contains all configuration for mail type MailConfig struct { AuthMailAddr string AuthPassword string SendFrom string SMTPHost string TLSSkipVerify bool } var config MailConfig func SendMail(mailto string, subject string, body string) error { // Code } ``` ## 2. Set From and To ``` golang from := mail.Address{ Name: "", Address: config.SendFrom, } to := mail.Address{ Name: "", Address: mailto, } ``` ## 3. Setup Header and Message ``` golang // Setup headers headers := make(map[string]string) headers["From"] = from.String() headers["To"] = to.String() headers["Subject"] = subject // Setup message message := "" for k, v := range headers { message += fmt.Sprintf("%s: %s\r\n", k, v) } message += "\r\n" + body ``` ## 4. Start Connection ``` golang // Connect to the SMTP Server host, _, _ := net.SplitHostPort(config.SMTPHost) auth := smtp.PlainAuth("", config.AuthMailAddr, config.AuthPassword, host) // TLS config tlsconfig := &tls.Config{ InsecureSkipVerify: config.TLSSkipVerify, ServerName: host, } c, err := smtp.Dial(config.SMTPHost) if err != nil { log.Panic(err) } c.StartTLS(tlsconfig) ``` ## 5. Auth and Send Data ``` golang // Auth if err = c.Auth(auth); err != nil { return err } // To && From if err = c.Mail(from.Address); err != nil { return err } if err = c.Rcpt(to.Address); err != nil { return err } // Data w, err := c.Data() if err != nil { return err } _, err = w.Write([]byte(message)) if err != nil { return err } err = w.Close() if err != nil { return err } c.Quit() ```
Pre:
How to Import Virtual Machine Image into AWS
Next: No Post
0
likes
361
新浪微博
微信
腾讯微博
QQ空间
人人网
Please enable JavaScript to view the
comments powered by Disqus.
comments powered by
Disqus
Table of content