From 6bec0e3964f03f776841cec5e639784222a33958 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sat, 31 Jul 2021 16:45:49 -0600 Subject: begin work on mailing list server, got the fundamental components done --- srv/mailinglist/mailer.go | 75 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 srv/mailinglist/mailer.go (limited to 'srv/mailinglist/mailer.go') diff --git a/srv/mailinglist/mailer.go b/srv/mailinglist/mailer.go new file mode 100644 index 0000000..81d0b91 --- /dev/null +++ b/srv/mailinglist/mailer.go @@ -0,0 +1,75 @@ +package mailinglist + +import ( + "github.com/emersion/go-sasl" + "github.com/emersion/go-smtp" +) + +// Mailer is used to deliver emails to arbitrary recipients. +type Mailer interface { + Send(to, subject, body string) error +} + +// MailerParams are used to initialize a new Mailer instance +type MailerParams struct { + SMTPAddr string + + // Optional, if not given then no auth is attempted. + SMTPAuth sasl.Client + + // The sending email address to use for all emails being sent. + SendAs string +} + +type mailer struct { + params MailerParams +} + +// NewMailer initializes and returns a Mailer which will use an external SMTP +// server to deliver email. +func NewMailer(params MailerParams) Mailer { + return &mailer{ + params: params, + } +} + +func (m *mailer) Send(to, subject, body string) error { + + msg := []byte("From: " + m.params.SendAs + "\r\n" + + "To: " + to + "\r\n" + + "Subject: " + subject + "\r\n\r\n" + + body + "\r\n") + + c, err := smtp.Dial(m.params.SMTPAddr) + if err != nil { + return err + } + defer c.Close() + + if err = c.Auth(m.params.SMTPAuth); err != nil { + return err + } + + if err = c.Mail(m.params.SendAs, nil); err != nil { + return err + } + + if err = c.Rcpt(to); err != nil { + return err + } + + w, err := c.Data() + if err != nil { + return err + } + + if _, err = w.Write(msg); err != nil { + return err + } + + if err = w.Close(); err != nil { + return err + } + + return c.Quit() +} -- cgit v1.2.3