Skip to content

Instantly share code, notes, and snippets.

@sandromello
Created November 4, 2020 16:38
Show Gist options
  • Save sandromello/1f4fbfd287521e5af62b046278a515fa to your computer and use it in GitHub Desktop.
Save sandromello/1f4fbfd287521e5af62b046278a515fa to your computer and use it in GitHub Desktop.
Smtp Send Example
package main
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"net"
"net/smtp"
"text/template"
)
type loginAuth struct {
username, password string
}
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte(a.username), nil
}
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(a.username), nil
case "Password:":
return []byte(a.password), nil
default:
return nil, errors.New("Unknown from server")
}
}
return nil, nil
}
func main() {
// Sender data.
from := ""
password := ""
// Receiver email address.
to := []string{
"[email protected]",
}
// smtp server configuration.
smtpHost := "smtp.gmail.com"
smtpPort := "587"
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", smtpHost, smtpPort))
if err != nil {
panic(err)
}
c, err := smtp.NewClient(conn, smtpHost)
if err != nil {
panic(err)
}
tlsconfig := &tls.Config{
ServerName: smtpHost,
}
if err = c.StartTLS(tlsconfig); err != nil {
panic(err)
}
auth := LoginAuth(from, password)
if err = c.Auth(auth); err != nil {
panic(err)
}
t, _ := template.ParseFiles("template.html")
var body bytes.Buffer
mimeHeaders := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
body.Write([]byte(fmt.Sprintf("Subject: This is a test subject \n%s\n\n", mimeHeaders)))
t.Execute(&body, struct {
Name string
Message string
}{
Name: "JohnDoe",
Message: "This is a test message in a HTML template",
})
// Sending email.
err = smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, body.Bytes())
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Email Sent!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment