-
Notifications
You must be signed in to change notification settings - Fork 0
/
smtp-mailer.go
82 lines (68 loc) · 1.62 KB
/
smtp-mailer.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
81
82
package mail
import (
"strings"
"time"
mail "github.com/xhit/go-simple-mail/v2"
)
func (m *Mailer) SendSMTPMessage(msg Message) error {
formattedMsg, err := m.buildHTMLMessage(msg)
if err != nil {
return err
}
plainTextMsg, err := m.buildPlainTextMessage(msg)
if err != nil {
return err
}
server := mail.NewSMTPClient()
server.Host = m.settings.Host
server.Port = m.settings.Port
server.Username = m.settings.Username
server.Password = m.settings.Password
// set encryption
switch strings.ToLower(m.settings.Encryption) {
case "tls":
server.Encryption = mail.EncryptionSTARTTLS
case "ssl":
server.Encryption = mail.EncryptionSSLTLS
case "none":
server.Encryption = mail.EncryptionNone
default:
server.Encryption = mail.EncryptionSTARTTLS
}
// set authentication
switch strings.ToLower(m.settings.AuthMethod) {
case "login":
server.Authentication = mail.AuthLogin
case "CRAMMD5":
server.Authentication = mail.AuthCRAMMD5
default:
server.Authentication = mail.AuthPlain
}
server.KeepAlive = false
server.ConnectTimeout = 15 * time.Second
server.SendTimeout = 15 * time.Second
smtpClient, err := server.Connect()
if err != nil {
return err
}
// set default from address
if msg.From == "" {
msg.From = m.settings.From
}
email := mail.NewMSG()
email.SetFrom(msg.From).
AddTo(msg.To...).
SetSubject(msg.Subject).
AddCc(msg.CC...).
AddBcc(msg.BCC...).
SetBody(mail.TextHTML, formattedMsg).
AddAlternative(mail.TextPlain, plainTextMsg)
for _, atch := range msg.Attachments {
email.AddAttachment(atch)
}
err = email.Send(smtpClient)
if err != nil {
return err
}
return nil
}