Skip to content

Instantly share code, notes, and snippets.

@muzea
Created December 1, 2018 08:47
Show Gist options
  • Save muzea/7d94835f635b7e7751c346208201a5f1 to your computer and use it in GitHub Desktop.
Save muzea/7d94835f635b7e7751c346208201a5f1 to your computer and use it in GitHub Desktop.
SMTP relay
package main
import (
"crypto/tls"
"log"
"net/smtp"
"io"
"io/ioutil"
gosmtp "github.com/emersion/go-smtp"
)
type Backend struct{}
func (bkd *Backend) Login(username, password string) (gosmtp.User, error) {
return &User{}, nil
}
// Require clients to authenticate using SMTP AUTH before sending emails
func (bkd *Backend) AnonymousLogin() (gosmtp.User, error) {
return &User{}, nil
}
type User struct{}
func (u *User) Send(from string, to []string, r io.Reader) error {
log.Println("Sending message:", from, to)
if b, err := ioutil.ReadAll(r); err != nil {
return err
} else {
go sendMail(to, string(b))
// log.Println("Data:", string(b))
}
return nil
}
func (u *User) Logout() error {
return nil
}
type Mail struct {
senderId string
toIds []string
}
type SmtpServer struct {
host string
port string
}
func (s *SmtpServer) ServerName() string {
return s.host + ":" + s.port
}
func sendMail(to []string, messageBody string) {
mail := Mail{}
mail.senderId = "我是邮箱账号"
mail.toIds = to
smtpServer := SmtpServer{host: "smtp.exmail.qq.com", port: "465"}
log.Println(smtpServer.host)
//build an auth
auth := smtp.PlainAuth("", mail.senderId, "我是密码", smtpServer.host)
// Gmail will reject connection if it's not secure
// TLS config
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: smtpServer.host,
}
conn, err := tls.Dial("tcp", smtpServer.ServerName(), tlsconfig)
if err != nil {
log.Panic(err)
}
client, err := smtp.NewClient(conn, smtpServer.host)
if err != nil {
log.Panic(err)
}
// step 1: Use Auth
if err = client.Auth(auth); err != nil {
log.Panic(err)
}
// step 2: add all from and to
if err = client.Mail(mail.senderId); err != nil {
log.Panic(err)
}
for _, k := range mail.toIds {
if err = client.Rcpt(k); err != nil {
log.Panic(err)
}
}
// Data
w, err := client.Data()
if err != nil {
log.Panic(err)
}
_, err = w.Write([]byte(messageBody))
if err != nil {
log.Panic(err)
}
err = w.Close()
if err != nil {
log.Panic(err)
}
client.Quit()
log.Println("Mail sent successfully")
}
func main() {
be := &Backend{}
s := gosmtp.NewServer(be)
s.Addr = ":2333"
s.Domain = "127.0.0.1"
s.MaxIdleSeconds = 300
s.MaxMessageBytes = 1024 * 1024
s.MaxRecipients = 50
s.AllowInsecureAuth = true
log.Println("Starting server at", s.Addr)
if err := s.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment