summaryrefslogtreecommitdiff
path: root/srv/mailinglist/mailer.go
diff options
context:
space:
mode:
authorBrian Picciano <mediocregopher@gmail.com>2021-07-31 16:45:49 -0600
committerBrian Picciano <mediocregopher@gmail.com>2021-07-31 16:52:16 -0600
commit6bec0e3964f03f776841cec5e639784222a33958 (patch)
tree468d195614e6e12197ff571ec94a46692a999059 /srv/mailinglist/mailer.go
parent0655b192833bc39404ae71ef47a1d348d718aeaf (diff)
begin work on mailing list server, got the fundamental components done
Diffstat (limited to 'srv/mailinglist/mailer.go')
-rw-r--r--srv/mailinglist/mailer.go75
1 files changed, 75 insertions, 0 deletions
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()
+}