-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmail.go
80 lines (65 loc) · 1.63 KB
/
gmail.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package email
import (
"context"
"fmt"
"net/smtp"
"os"
"testing"
"github.com/jordan-wright/email"
"github.com/qiushiyan/simplebank/business/report"
)
// GmailSender is an email sender that sends emails using Gmail.
type GmailSender struct {
// Address is the email address to send from, currently only supports Gmail.
address string
// Password is the **app password** for the gmail account
password string
}
func NewGmailSender(address, password string) *GmailSender {
return &GmailSender{
address: address,
password: password,
}
}
func (s GmailSender) Send(payload *SenderPayload) error {
var subject string
var err error
e := email.NewEmail()
switch payload.Subject {
case SubjectWelcome:
subject = "Welcome to SimpleBank!"
case SubjectVerify:
subject = "Verify your email"
case SubjectReport:
subject = "Your activity report"
reportGenerator := report.NewQuartoGenerator()
outputFileName, err := reportGenerator.New(
context.Background(),
report.SubjectActivity,
report.SubjectActivityData{
Username: payload.Data.(SubjectReportData).Username,
},
)
if err != nil {
return fmt.Errorf("could not generate report: %w", err)
}
defer os.Remove(outputFileName)
e.AttachFile(outputFileName)
default:
return ErrInvalidSubject
}
e.From = "SimpleBank <simplebankdev@gmail.com>"
e.To = []string{payload.To}
e.Subject = subject
e.HTML, err = getEmailHTML(payload)
if err != nil {
return fmt.Errorf("could not get email template: %w", err)
}
if testing.Testing() {
return nil
}
return e.Send(
"smtp.gmail.com:587",
smtp.PlainAuth("", s.address, s.password, "smtp.gmail.com"),
)
}