From 66642b894fc6b8028cafa552a377f9f9067a1850 Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Wed, 23 Nov 2022 16:29:59 -0600 Subject: [PATCH] Adding email attachment support to Helper struct --- email/helper.go | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/email/helper.go b/email/helper.go index 4e100bb..355ad6e 100644 --- a/email/helper.go +++ b/email/helper.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "html/template" + "io" "hg.code.netlandish.com/~netlandish/gobwebs" "petersanchez.com/carrier" @@ -21,11 +22,25 @@ type Helper struct { tmap TMap tmpl *template.Template IgnoreHTMLErrors bool + attachments []*Attachment +} + +// Attachment is a struct to pass in email attachments to a carrier +// email message. +type Attachment struct { + filename string + data io.Reader + ctype string } // NewHelper returns a new email Helper func NewHelper(queue *ServiceQueue, tmap TMap, t *template.Template) *Helper { - return &Helper{queue, tmap, t, false} + return &Helper{ + q: queue, + tmap: tmap, + tmpl: t, + IgnoreHTMLErrors: false, + } } // Map ... @@ -33,6 +48,22 @@ func (h *Helper) Map() TMap { return h.tmap } +// Attach adds an email attachment +func (h *Helper) Attach(fname string, data io.Reader, ctype string) error { + if data == nil { + return fmt.Errorf("You must send data to be used as an attachment") + } + if fname == "" { + return fmt.Errorf("You must send a filename for the attachment") + } + + if h.attachments == nil { + h.attachments = make([]*Attachment, 0) + } + h.attachments = append(h.attachments, &Attachment{fname, data, ctype}) + return nil +} + // Send sends the email func (h *Helper) Send(name, from, rcpt string, data gobwebs.Map) error { if _, ok := h.tmap[name]; !ok { @@ -85,5 +116,11 @@ func (h *Helper) Send(name, from, rcpt string, data gobwebs.Map) error { return err } } + if h.attachments != nil { + for _, a := range h.attachments { + msg.AddAttachment(a.filename, a.data, a.ctype) + } + h.attachments = nil // Null out attachments slice + } return h.q.SendMail(msg) } -- 2.45.2