-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotif_client_smtp.go
105 lines (86 loc) · 2.06 KB
/
notif_client_smtp.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// SPDX-FileCopyrightText: 2023 M. Shulhan <[email protected]>
// SPDX-License-Identifier: GPL-3.0-or-later
package karajo
import (
"fmt"
"git.sr.ht/~shulhan/pakakeh.go/lib/email"
"git.sr.ht/~shulhan/pakakeh.go/lib/mlog"
"git.sr.ht/~shulhan/pakakeh.go/lib/smtp"
)
// clientSMTP client for SMTP.
type clientSMTP struct {
conn *smtp.Client
opts smtp.ClientOptions
env EnvNotif
}
// newClientSMTP create new client for SMTP.
func newClientSMTP(envNotif EnvNotif) (cl *clientSMTP, err error) {
var logp = `newClientSMTP`
cl = &clientSMTP{
env: envNotif,
opts: smtp.ClientOptions{
ServerURL: envNotif.SMTPServer,
AuthUser: envNotif.SMTPUser,
AuthPass: envNotif.SMTPPassword,
AuthMechanism: smtp.SaslMechanismPlain,
Insecure: envNotif.SMTPInsecure,
},
}
// Test connecting and authenticated with the server.
cl.conn, err = smtp.NewClient(cl.opts)
if err != nil {
return nil, fmt.Errorf(`%s: %s: %w`, logp, cl.opts.ServerURL, err)
}
_, _ = cl.conn.Quit()
return cl, nil
}
// Send the job status and log to user.
func (cl *clientSMTP) Send(jlog *JobLog) {
var (
logp = `clientSMTP.Send`
msg = email.Message{}
v string
data []byte
err error
)
err = msg.SetFrom(cl.env.From)
if err != nil {
mlog.Errf(`%s: %s`, logp, err)
return
}
for _, v = range cl.env.To {
err = msg.AddTo(v)
if err != nil {
mlog.Errf(`%s: To %s: %s`, logp, v, err)
return
}
}
v = fmt.Sprintf(`%s: %s: #%d: %s`, jlog.jobKind, jlog.JobID, jlog.Counter, jlog.Status)
msg.SetSubject(v)
err = msg.SetBodyText(jlog.content)
if err != nil {
mlog.Errf(`%s: %s`, logp, err)
return
}
data, err = msg.Pack()
if err != nil {
mlog.Errf(`%s: %s`, logp, err)
return
}
var mailtx = smtp.NewMailTx(cl.env.From, cl.env.To, data)
cl.conn, err = smtp.NewClient(cl.opts)
if err != nil {
mlog.Errf(`%s: %s: %s`, logp, cl.opts.ServerURL, err)
return
}
_, err = cl.conn.MailTx(mailtx)
if err != nil {
mlog.Errf(`%s: %s`, logp, err)
return
}
_, err = cl.conn.Quit()
if err != nil {
mlog.Errf(`%s: %s`, logp, err)
return
}
}