Skip to content

Instantly share code, notes, and snippets.

@thrawn01
Last active October 6, 2023 20:10
Show Gist options
  • Save thrawn01/8beccf44ca238466dc95dc50c2def09d to your computer and use it in GitHub Desktop.
Save thrawn01/8beccf44ca238466dc95dc50c2def09d to your computer and use it in GitHub Desktop.
Basic SMTP Client
package main
import (
"crypto/tls"
"fmt"
"log"
"net"
"net/smtp"
)
func main() {
addr := "smtp.server.com:587"
conn, err := tls.Dial("tcp", addr, &tls.Config{})
host, _, _ := net.SplitHostPort(addr)
c, err := smtp.NewClient(conn, host)
if err != nil {
log.Fatal(err)
}
creds := smtp.PlainAuth("mailgun.net", "[email protected]", "", "localhost")
if err := c.Auth(creds); err != nil {
log.Printf("during auth")
log.Fatal(err)
}
// Set the sender and recipient first
if err := c.Mail("[email protected]"); err != nil {
log.Printf("during mail")
log.Fatal(err)
}
if err := c.Rcpt("[email protected]"); err != nil {
log.Printf("during rcpt")
log.Fatal(err)
}
// Send the email body.
wc, err := c.Data()
if err != nil {
log.Printf("during data")
log.Fatal(err)
}
_, err = fmt.Fprintf(wc, "This is the email body")
if err != nil {
log.Printf("during data send")
log.Fatal(err)
}
err = wc.Close()
if err != nil {
log.Printf("during close")
log.Fatal(err)
}
// Send the QUIT command and close the connection.
err = c.Quit()
if err != nil {
log.Printf("during quit")
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment