Created
November 30, 2015 23:03
-
-
Save kennwhite/ba9c4015fac2b23ceab2 to your computer and use it in GitHub Desktop.
Simple example of sending email with StartTLS in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Simple example of sending an email with StartTLS in Go | |
See: https://golang.org/pkg/net/smtp/#SendMail for TLS defaults | |
*/ | |
package main | |
import ( | |
"log" | |
"net/smtp" | |
"os" | |
) | |
const SMTP_USER_ENV string = "SMTP_USER" | |
const SMTP_PWD_ENV string = "SMTP_PWD" | |
const SMTP_ENDPOINT string = "email-smtp.us-east-1.amazonaws.com" | |
const SMTP_PORT string = ":587" | |
type Mail struct { | |
ToName string | |
ToAddr string | |
FromName string | |
FromAddr string | |
Subject string | |
Body string | |
} | |
func mailer(m Mail) error { | |
smtp_user := os.Getenv(SMTP_USER_ENV) | |
if smtp_user == "" { | |
log.Fatal("Deploy: Unable to retrieve SMTP user. Make sure environment sets: " + SMTP_USER_ENV) | |
} | |
smtp_pwd := os.Getenv(SMTP_PWD_ENV) | |
if smtp_pwd == "" { | |
log.Fatal("Deploy: Unable to retrieve SMTP password. Make sure environment sets: " + SMTP_PWD_ENV) | |
} | |
mailer := SMTP_ENDPOINT | |
msg := []byte( "From: " + m.FromName + " <" + m.FromAddr + ">" + "\r\n" + | |
"To: " + m.ToAddr + "\r\n" + | |
"Subject: " + m.Subject + "\r\n\r\n" + | |
m.Body + "\r\n" ) | |
auth := smtp.PlainAuth("", smtp_user, smtp_pwd, mailer) | |
err := smtp.SendMail(mailer+SMTP_PORT, auth, m.FromAddr, []string{m.ToAddr}, msg) | |
return err | |
} | |
func main() { | |
m := Mail{ ToAddr: "recipient@example.com", | |
FromName: "Sender's Name", | |
FromAddr: "sender@example.com", | |
Subject: "Subject line", | |
Body: "Test email. \r\n Test, test." } | |
err := mailer(m) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment