Skip to content

Instantly share code, notes, and snippets.

@olafurjohannsson
Created July 10, 2016 11:31
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 olafurjohannsson/2e8fbd3b7c504f0eb2723f7808eb540f to your computer and use it in GitHub Desktop.
Save olafurjohannsson/2e8fbd3b7c504f0eb2723f7808eb540f to your computer and use it in GitHub Desktop.
Send email with Go
package EmailSender
import (
"net/smtp"
"strconv"
)
type EmailSender interface {
Send() error
Create() EmailMessage
Init() * EmailAuth
}
type EmailAuth struct {
User string
Password string
Hostname string
Identity string
Port int
}
type EmailMessage struct {
To []string
From string
Body []byte
}
// Create mail client
func Init(user string, password string, hostname string, port int, identity string) *EmailAuth {
return &EmailAuth{
User: user,
Password: password,
Hostname: hostname,
Port: port,
Identity: identity,
}
}
// Create email
func Create(to []string, from string, body []byte) EmailMessage {
return EmailMessage{
To: to,
From: from,
Body: body,
}
}
// Send email
func Send(email EmailMessage, emailAuth EmailAuth) error {
auth := smtp.PlainAuth(emailAuth.Identity, emailAuth.User, emailAuth.Password, emailAuth.Hostname)
err := smtp.SendMail(emailAuth.Hostname + ":" + strconv.Itoa(emailAuth.Port), auth, email.From, email.To, email.Body)
if err != nil {
return err
}
return nil
}
package main
import (
"./EmailSender"
"fmt"
)
func main() {
// Create mail client
client := EmailSender.Init("user@gmail.com", "useremail", "smtp.gmail.com", 587, "")
// Create email
mail := EmailSender.Create([]string{"recepitientsemail"}, "user@gmail.com", []byte("subject in email"))
// try to send email
err := EmailSender.Send(mail, *client)
if err != nil {
fmt.Printf("Error: %s\n", err)
} else {
fmt.Printf("Email sent!\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment