Created
July 10, 2016 11:31
-
-
Save olafurjohannsson/2e8fbd3b7c504f0eb2723f7808eb540f to your computer and use it in GitHub Desktop.
Send email with Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"./EmailSender" | |
"fmt" | |
) | |
func main() { | |
// Create mail client | |
client := EmailSender.Init("[email protected]", "useremail", "smtp.gmail.com", 587, "") | |
// Create email | |
mail := EmailSender.Create([]string{"recepitientsemail"}, "[email protected]", []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