Skip to content

Instantly share code, notes, and snippets.

@ik5
Last active August 29, 2015 14:06
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 ik5/48aa7ca0f960ff81e3e7 to your computer and use it in GitHub Desktop.
Save ik5/48aa7ca0f960ff81e3e7 to your computer and use it in GitHub Desktop.
Sending email using Go
package main
import (
"fmt"
"github.com/alexcesaro/mail/gomail"
"net/smtp"
)
type Email struct {
From string
FromName string
To []string
Subject string
Body string
HTML string
Attachment string
Server string
UserName string
Password string
Port uint16
}
func full_host(email Email) string {
return fmt.Sprintf("%s:%d", email.Server, email.Port)
}
func Natural_Mail(email Email) error {
auth := smtp.PlainAuth("", email.UserName, email.Password, email.Server)
host := full_host(email)
msg := []byte("Subject: " + email.Subject + "\r\n\r\n" + email.Body)
return smtp.SendMail(host, auth, email.From, email.To, msg)
}
func Go_Mail(email Email) error {
msg := gomail.NewMessage()
msg.SetAddressHeader("From", email.From, email.FromName)
for i, v := range email.To {
if i == 0 {
msg.SetHeader("To", v)
} else {
msg.AddHeader("To", v)
}
}
msg.SetHeader("Subject", email.Subject)
msg.SetBody("text/plain", email.Body)
if email.HTML != "" {
msg.AddAlternative("text/html", email.HTML)
}
if email.Attachment != "" {
err := msg.Attach(email.Attachment)
if err != nil {
return err
}
}
var m gomail.Mailer
if email.Port != 25 {
auth := smtp.PlainAuth("", email.UserName, email.Password, email.Server)
host := full_host(email)
m = gomail.NewCustomMailer(auth, host)
} else {
m = gomail.NewMailer(email.Server, email.UserName, email.Password, int(email.Port))
}
return m.Send(msg)
}
func main() {
email := Email{
From: "alice@example.com",
FromName: "Alice",
To: []string{"bob@example.com", "cat@example.com"},
Subject: "Testing email using Go",
Body: "Testing email using Go",
HTML: "<h1>Welcome</h1><br>\n" +
"Testing email using Go",
Server: "smtp.gmail.com",
UserName: "alice",
Password: "password",
Port: 25,
}
fmt.Println("Going to use Go_Mail")
err := Go_Mail(email)
if err != nil {
fmt.Printf("Unable to send email using Go_Mail: %s", err)
}
fmt.Println("Going to use Natural_Mail")
err = Natural_Mail(email)
if err != nil {
fmt.Printf("Unable to send email using Natural_Mail: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment