Created
February 15, 2017 18:15
-
-
Save shantanoo/a4cf11833dfd68a0d2c621ba0286ee8f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"crypto/tls" | |
"fmt" | |
"github.com/jpoehls/gophermail" | |
"log" | |
"net" | |
"net/smtp" | |
) | |
func main() { | |
m := &gophermail.Message{} | |
m.SetFrom("Domain Sender <[email protected]>") | |
m.AddTo("First person <[email protected]>") | |
m.AddCc("Second person <[email protected]>") | |
message, err = m.Bytes() | |
if err != nil { | |
log.Panic(err) | |
} | |
// Connect to the SMTP Server | |
servername := "smtp.example.tld:465" | |
host, _, _ := net.SplitHostPort(servername) | |
auth := smtp.PlainAuth("", "[email protected]", "password", host) | |
// TLS config | |
tlsconfig := &tls.Config{ | |
InsecureSkipVerify: true, | |
ServerName: host, | |
} | |
// Here is the key, you need to call tls.Dial instead of smtp.Dial | |
// for smtp servers running on 465 that require an ssl connection | |
// from the very beginning (no starttls) | |
conn, err := tls.Dial("tcp", servername, tlsconfig) | |
if err != nil { | |
log.Panic(err) | |
} | |
c, err := smtp.NewClient(conn, host) | |
if err != nil { | |
log.Panic(err) | |
} | |
// Auth | |
if err = c.Auth(auth); err != nil { | |
log.Panic(err) | |
} | |
// To && From | |
if err = c.Mail(from.Address); err != nil { | |
log.Panic(err) | |
} | |
for _, recipient := range m.To { | |
if err = c.Rcpt(recipient.Address); err != nil { | |
log.Panic(err) | |
} | |
} | |
for _, recipient := range m.Cc { | |
if err = c.Rcpt(recipient.Address); err != nil { | |
log.Panic(err) | |
} | |
} | |
for _, recipient := range m.Bcc { | |
if err = c.Rcpt(recipient.Address); err != nil { | |
log.Panic(err) | |
} | |
} | |
// Data | |
w, err := c.Data() | |
if err != nil { | |
log.Panic(err) | |
} | |
_, err = w.Write(message) | |
if err != nil { | |
log.Panic(err) | |
} | |
err = w.Close() | |
if err != nil { | |
log.Panic(err) | |
} | |
c.Quit() | |
} | |
// Credit: https://gist.github.com/chrisgillis/10888032 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment