Skip to content

Instantly share code, notes, and snippets.

@guilyx
Created August 26, 2020 13:46
Show Gist options
  • Save guilyx/99119f6efb06487d6a94fe52ef9a05ce to your computer and use it in GitHub Desktop.
Save guilyx/99119f6efb06487d6a94fe52ef9a05ce to your computer and use it in GitHub Desktop.
A simple to use email wrapper
package main
import (
"fmt"
"net/smtp"
"strconv"
)
func SmtpAuthentification(username string, pwd string, host string) smtp.Auth {
return (smtp.PlainAuth("", username, pwd, host))
}
func SendEmail(auth smtp.Auth, host string, hostPort int, username string, targets []string, ccTo []string, subject string, content string) error {
destHeader := "To: "
i := 0
for _, dest := range targets {
if i > 1 {
destHeader = destHeader + ", " + dest
} else {
destHeader = destHeader + dest
}
i += 1
}
destHeader = destHeader + "\r\n"
i = 0
ccHeader := "cc: "
for _, cced := range ccTo {
if i > 1 {
ccHeader = ccHeader + ", " + cced
} else {
ccHeader = ccHeader + cced
}
i += 1
}
ccHeader = ccHeader + "\r\n"
obj := "Subject: " + subject + "\r\n"
finalContent := content + "\r\n"
var msg []byte
if ccTo == nil {
msg = []byte(destHeader + obj + finalContent)
} else {
msg = []byte(destHeader + ccHeader + obj + finalContent)
targets = append(targets, ccTo...)
}
if len(msg) == 0 {
return fmt.Errorf("Cannot send email with 0 bytes as content")
}
smtpHost := host + ":" + strconv.Itoa(hostPort)
err := smtp.SendMail(smtpHost, auth, username, targets, msg)
if err != nil {
fmt.Printf("Error: %s\n", err)
return fmt.Errorf("Failed to send email with subject [%s] to [%s]", subject, targets[0])
}
return nil
}
func main() {
username := "johndoe"
smtpHost := "smtp.gmail.com"
smtpPort := 587
pwd := "fakepassword"
recipients := []string{"mugiwara@noluffy.cn", "sanji@vinsmoke.fr"}
ccTo := []string{"roronoa@zoro.jp"}
subject := "Kaizoku oni ore wa naru"
content := "Basically means that I'm going to be the pirate king.\r\n Could be powerful if combined with go-template.go (another one of my gists)"
auth := SmtpAuthentification(username, pwd, smtpHost)
err := SendEmail(auth, smtpHost, smtpPort, username, recipients, ccTo, subject, content)
if err != nil {
fmt.Printf("Sending email failed with error: %v", err)
panic("haaaaaaaaaaaa!")
}
fmt.Println("Successfuly sent requested email. Yay!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment