Skip to content

Instantly share code, notes, and snippets.

@wotmshuaisi
Created August 8, 2024 07:06
Show Gist options
  • Save wotmshuaisi/9776781780c94e8888fa2ea1930f5d69 to your computer and use it in GitHub Desktop.
Save wotmshuaisi/9776781780c94e8888fa2ea1930f5d69 to your computer and use it in GitHub Desktop.
Golang sending emails over port 587 with InsecureSkipVerify.
package utils
import (
"crypto/tls"
"fmt"
"net/mail"
"net/smtp"
"strings"
)
var (
smtpPort = "587"
smtpHost = "example.com"
smtpUser = "[email protected]"
smtpAuth = smtp.PlainAuth("", smtpUser, "password", smtpHost)
)
func SendMail1(emails []string, body []byte) {
if len(emails) < 1 {
return
}
from := mail.Address{Address: smtpUser}
body = append([]byte(fmt.Sprintf("From: %s\r\n", from.String())), body...)
body = append([]byte(fmt.Sprintf("To: %s\r\n", strings.Join(emails, ","))), body...)
smtpClient, err := smtp.Dial(fmt.Sprintf("%s:%s", smtpHost, smtpPort))
if err != nil {
panic(err)
}
defer smtpClient.Close()
if ok, _ := smtpClient.Extension("STARTTLS"); ok {
config := &tls.Config{ServerName: smtpHost, InsecureSkipVerify: true}
if err = smtpClient.StartTLS(config); err != nil {
panic(err)
}
}
if err = smtpClient.Auth(smtpAuth); err != nil {
panic(err)
}
if err = smtpClient.Mail(from.Address); err != nil {
panic(err)
}
for _, addr := range emails {
if err = smtpClient.Rcpt(addr); err != nil {
panic(err)
}
}
w, err := smtpClient.Data()
if err != nil {
panic(err)
}
_, err = w.Write(body)
if err != nil {
panic(err)
}
err = w.Close()
if err != nil {
panic(err)
}
smtpClient.Quit()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment