-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.go
79 lines (71 loc) · 1.72 KB
/
mail.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
package utils
import (
"bytes"
"crypto/tls"
"fmt"
"html/template"
"time"
mail "github.com/xhit/go-simple-mail/v2"
)
// Mailer encapsulates the dependency
type Mailer struct {
*mail.SMTPClient
Enabled bool
}
// MailConfig represents a configuration to connect to an SMTP server
type MailConfig struct {
Host string
Port int
Username string
Password string
}
// Mail represents an email to be sent
type Mail struct {
Subject string
To string
Cc []string
Bcc []string
From string
tpl template.Template
tplData interface{}
}
// NewMailer creates a new SMTP client
func NewMailer(config MailConfig) (*Mailer, error) {
smtpServer := mail.SMTPServer{
Host: config.Host,
Port: config.Port,
Username: config.Username,
Password: config.Password,
Encryption: mail.EncryptionTLS,
Authentication: mail.AuthPlain,
ConnectTimeout: 10 * time.Second,
SendTimeout: 10 * time.Second,
TLSConfig: &tls.Config{InsecureSkipVerify: true},
}
smtpClient, err := smtpServer.Connect()
if err != nil {
return &Mailer{nil, false}, err
}
return &Mailer{smtpClient, true}, nil
}
// SendMail sends a template email
func (m *Mailer) SendMail(item Mail) error {
body := bytes.Buffer{}
err := item.tpl.Execute(&body, item.tplData)
if err != nil {
return fmt.Errorf("failed to exec tpl: %w", err)
}
email := mail.NewMSG()
email.SetFrom(item.From).AddTo(item.To).SetSubject(item.Subject)
if len(item.Cc) != 0 {
email.AddCc(item.Cc...)
}
if len(item.Bcc) != 0 {
email.AddBcc(item.Bcc...)
}
email.SetBody(mail.TextHTML, body.String())
if email.Error != nil {
return fmt.Errorf("failed to set mail data: %w", email.Error)
}
return email.Send(m.SMTPClient)
}