forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmtp_mailer_service.go
More file actions
58 lines (49 loc) · 1.31 KB
/
Copy pathsmtp_mailer_service.go
File metadata and controls
58 lines (49 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package emails
import (
"context"
"fmt"
"net/smtp"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
mail "github.com/jordan-wright/email"
"github.com/palantir/stacktrace"
)
// SMTPConfig is the config for setting up the smtpMailer
type SMTPConfig struct {
FromName string
FromEmail string
Username string
Password string
Hostname string
Port string
}
type smtpMailer struct {
address string
from string
tracer telemetry.Tracer
auth smtp.Auth
}
// NewSMTPEmailService creates a new instance of the smtpMailer
func NewSMTPEmailService(tracer telemetry.Tracer, config SMTPConfig) Mailer {
return &smtpMailer{
tracer: tracer,
auth: smtp.PlainAuth("", config.Username, config.Password, config.Hostname),
address: fmt.Sprintf("%s:%s", config.Hostname, config.Port),
from: fmt.Sprintf("%s <%s>", config.FromName, config.FromEmail),
}
}
// Send a new email
func (mailer *smtpMailer) Send(ctx context.Context, email *Email) (err error) {
ctx, span := mailer.tracer.Start(ctx)
defer span.End()
e := mail.NewEmail()
e.From = mailer.from
e.To = []string{email.toAddress()}
e.Subject = email.Subject
e.Text = []byte(email.Text)
e.HTML = []byte(email.HTML)
err = e.Send(mailer.address, mailer.auth)
if err != nil {
return stacktrace.Propagate(err, "cannot send email")
}
return nil
}