Skip to content

Instantly share code, notes, and snippets.

@rickt
Last active December 30, 2015 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickt/7817444 to your computer and use it in GitHub Desktop.
Save rickt/7817444 to your computer and use it in GitHub Desktop.
HOW-TO: send email via SMTP with Go.
package main
import (
"crypto/tls"
"fmt"
"log"
"net"
"net/mail"
"net/smtp"
)
func main() {
// the basics
from := mail.Address{"senders name", "username@sender.com"}
to := mail.Address{"recipients name", "username@recipient.com"}
body := "this is the body line1.\nthis is the body line2.\nthis is the body line3.\n"
subject := "this is the subject line"
// setup the remote smtpserver & auth info
smtpserver := "remote.mailserver.com:25"
auth := smtp.PlainAuth("", "username@sender.com", "senders-password", "remote.mailserver.com")
// setup a map for the headers
header := make(map[string]string)
header["From"] = from.String()
header["To"] = to.String()
header["Subject"] = subject
// setup the message
message := ""
for k, v := range header {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + body
// create the smtp connection
c, err := smtp.Dial(smtpserver)
if err != nil {
log.Panic(err)
}
// set some TLS options, so we can make sure a non-verified cert won't stop us sending
host, _, _ := net.SplitHostPort(smtpserver)
// make a nice tls.Config struct
tlc := &tls.Config{
InsecureSkipVerify: true,
ServerName: host,
}
// send the tls.Config to StartTLS to generate the STARTTLS
if err = c.StartTLS(tlc); err != nil {
log.Panic(err)
}
// let's authenticate
if err = c.Auth(auth); err != nil {
log.Panic(err)
}
// To && From
if err = c.Mail(from.Address); err != nil {
log.Panic(err)
}
// Recipient
if err = c.Rcpt(to.Address); err != nil {
log.Panic(err)
}
// Data
w, err := c.Data()
if err != nil {
log.Panic(err)
}
// everything is setup; write it
_, err = w.Write([]byte(message))
if err != nil {
log.Panic(err)
}
err = w.Close()
if err != nil {
log.Panic(err)
}
c.Quit()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment