Refactor Messenger/Emailer to accept attachments

This commit is contained in:
Kailash Nadh 2019-07-18 12:40:48 +05:30
parent 533caf894b
commit 81d3046374
5 changed files with 36 additions and 9 deletions

View File

@ -509,7 +509,7 @@ func sendTestMessage(sub *models.Subscriber, camp *models.Campaign, app *App) er
fmt.Sprintf("Error rendering message: %v", err))
}
if err := app.Messenger.Push(camp.FromEmail, []string{sub.Email}, camp.Subject, m.Body); err != nil {
if err := app.Messenger.Push(camp.FromEmail, []string{sub.Email}, camp.Subject, m.Body, nil); err != nil {
return err
}

View File

@ -238,7 +238,7 @@ func (m *Manager) SpawnWorkers() {
msg.from,
[]string{msg.to},
msg.Campaign.Subject,
msg.Body)
msg.Body, nil)
if err != nil {
m.logger.Printf("error sending message in campaign %s: %v",
msg.Campaign.Name, err)

View File

@ -66,7 +66,7 @@ func (e *emailer) Name() string {
}
// Push pushes a message to the server.
func (e *emailer) Push(fromAddr string, toAddr []string, subject string, m []byte) error {
func (e *emailer) Push(fromAddr string, toAddr []string, subject string, m []byte, atts []*Attachment) error {
var key string
// If there are more than one SMTP servers, send to a random
@ -77,12 +77,28 @@ func (e *emailer) Push(fromAddr string, toAddr []string, subject string, m []byt
key = e.serverNames[0]
}
// Are there attachments?
var files []*email.Attachment
if atts != nil {
files = make([]*email.Attachment, 0, len(atts))
for _, f := range atts {
a := &email.Attachment{
Filename: f.Name,
Header: f.Header,
Content: make([]byte, len(f.Content)),
}
copy(a.Content, f.Content)
files = append(files, a)
}
}
srv := e.servers[key]
err := srv.mailer.Send(&email.Email{
From: fromAddr,
To: toAddr,
Subject: subject,
HTML: m,
From: fromAddr,
To: toAddr,
Subject: subject,
HTML: m,
Attachments: files,
}, srv.SendTimeout)
return err

View File

@ -1,10 +1,20 @@
package messenger
import "net/textproto"
// Messenger is an interface for a generic messaging backend,
// for instance, e-mail, SMS etc.
type Messenger interface {
Name() string
Push(fromAddr string, toAddr []string, subject string, message []byte) error
Push(fromAddr string, toAddr []string, subject string, message []byte, atts []*Attachment) error
Flush() error
}
// Attachment represents a file or blob attachment that can be
// sent along with a message by a Messenger.
type Attachment struct {
Name string
Header textproto.MIMEHeader
Content []byte
}

View File

@ -22,7 +22,8 @@ func sendNotification(tpl, subject string, data map[string]interface{}, app *App
err = app.Messenger.Push(app.Constants.FromEmail,
app.Constants.NotifyEmails,
subject,
b.Bytes())
b.Bytes(),
nil)
if err != nil {
app.Logger.Printf("error sending admin notification (%s): %v", subject, err)
return err