-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemail.go
executable file
·276 lines (220 loc) · 7.3 KB
/
email.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package gosmtp
import (
"crypto/rand"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"log"
"net/mail"
"net/smtp"
"os"
"path/filepath"
"strings"
)
// emailValid validates an email.
func emailValid(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}
// getRandString returns a random string.
func getRandString() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x%x%x", b[0:4], b[4:6], b[6:8])
}
// addAttachments creates headers and 64based text;
// and adds it to the msg headers.
func addAttachments(bndry string, attch []string, msgHeaders string) string {
for i := 0; i < len(attch); i++ {
fPath := attch[i]
bFile, err := os.ReadFile(fPath)
fileName := filepath.Base(fPath)
if err != nil {
continue
}
// convert bytes to base64 string
b64Str := base64.StdEncoding.EncodeToString(bFile)
// this is the separator for each section
msgHeaders = fmt.Sprintf("%s--%s\r\n", msgHeaders, bndry)
msgHeaders = fmt.Sprintf("%sContent-Type: application/octet-stream; name=\"%s\"\r\n", msgHeaders, fileName)
msgHeaders = fmt.Sprintf("%sContent-Disposition: attachment; filename=\"%s\"\r\n", msgHeaders, fileName)
msgHeaders = fmt.Sprintf("%sContent-Transfer-Encoding: base64\r\n", msgHeaders)
msgHeaders = fmt.Sprintf("%s\r\n%s\r\n", msgHeaders, b64Str)
}
return msgHeaders
}
// prepareHeaders creates message headers.
// smtp message format:
//
// From: "<name goes here>" <<email goes here>>
// To: "<name goes here>" <<email goes here>>
// for multiple recipients, just add another string separated by comma (on the same line)
// e.g.
// "<name_1>" <<email_1>>,"<name_2>" <<email_2>>,...
//
// Cc: "<name goes here>" <<email goes here>>
// for multiple recipients: same as the above
//
// Subject: <subject goes here>
//
// for multipart (body text + attachments) see : https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
func prepareHeaders(m MailItem) string {
var headerTo []string
var headerCC []string
fromHeader := fmt.Sprintf(`"%s" <%s>`, m.From.Name, m.From.Address)
// To
for i := 0; i < len(m.To); i++ {
s := fmt.Sprintf(`"%s" <%s>`, m.To[i].Name, m.To[i].Address)
headerTo = append(headerTo, s)
}
// CC
for i := 0; i < len(m.CC); i++ {
s := fmt.Sprintf(`"%s" <%s>`, m.CC[i].Name, m.CC[i].Address)
headerCC = append(headerCC, s)
}
bndry := getRandString()
msgHeaders := ""
// conact lines into a single string
msgHeaders = fmt.Sprintf("%s%s:%s\r\n", msgHeaders, "From", fromHeader)
msgHeaders = fmt.Sprintf("%s%s:%s\r\n", msgHeaders, "To", strings.Join(headerTo, ","))
msgHeaders = fmt.Sprintf("%s%s:%s\r\n", msgHeaders, "Cc", strings.Join(headerCC, ","))
msgHeaders = fmt.Sprintf("%s%s:%s\r\n", msgHeaders, "Subject", m.Subject)
// add a message-id
fromDomain := strings.Split(m.From.Address, "@")[1]
b := make([]byte, 18)
rand.Read(b)
srnd := fmt.Sprintf("%x-%x-%x_%x%x", b[0:4], b[4:8], b[6:9], b[4:10], b[5:10])
msgID := fmt.Sprintf("%s@%s", srnd, fromDomain)
msgHeaders = fmt.Sprintf("%s%s:%s\r\n", msgHeaders, "Message-Id", msgID)
// add the recipient's receipt
if m.DispositionNotificationTo != "" {
msgHeaders = fmt.Sprintf("%sDisposition-Notification-To: \"%s\" <%s>\r\n", msgHeaders, m.DispositionNotificationTo, m.DispositionNotificationTo)
}
if m.Priority > 5 || m.Priority < 1 {
m.Priority = Normal
}
msgHeaders = fmt.Sprintf("%sX-Priority: %d (%s)\r\n", msgHeaders, m.Priority, m.Priority.String())
if m.Language != "" {
msgHeaders = fmt.Sprintf("%sContent-Language: %s\r\n", msgHeaders, m.Language)
}
// User-Agent
if m.UserAgent != "" {
msgHeaders = fmt.Sprintf("%sUser-Agent: %s\r\n", msgHeaders, m.UserAgent)
}
// add multipart/mixed and set the boundary, even if there is no attachments
msgHeaders = fmt.Sprintf("%sContent-Type: multipart/mixed; boundary=\"%s\"\r\n\r\n", msgHeaders, bndry)
// add body text
if m.TextBody != "" {
msgHeaders = fmt.Sprintf("%s--%s\r\n", msgHeaders, bndry)
msgHeaders = fmt.Sprintf("%sContent-Type: text/plain; charset=utf-8\r\n\r\n", msgHeaders)
msgHeaders = fmt.Sprintf("%s%s\r\n\r\n", msgHeaders, m.TextBody)
}
// add body html
if m.HTMLBody != "" {
bodyHTML := strings.ReplaceAll(htmlTemplate, "{{.Body}}", m.HTMLBody)
msgHeaders = fmt.Sprintf("%s--%s\r\n", msgHeaders, bndry)
msgHeaders = fmt.Sprintf("%sContent-Type: text/html; charset=utf-8\r\n\r\n", msgHeaders)
msgHeaders = fmt.Sprintf("%s%s\r\n\r\n", msgHeaders, bodyHTML)
}
// attachemnets if any
msgHeaders = addAttachments(bndry, m.Attachment, msgHeaders)
return msgHeaders
}
// sendMessage sends an smtp message.
// Go's smtp package does not have an option to send
// delivery status notification as of version 1.22.
// To enable this option, rename github.com.kambahr.go-smtp.smtp_notify.go.txt
// to github.com.kambahr.go-smtp.smtp_notify.go and copy it to .../go/src/net/smtp
// (i.e. /usr/local/go/src/net/smtp).
// Note that the SMTP server must support this option to begin with.
func sendMessage(m MailItem, mc MailCredentials, msgHeaders string) error {
// Connect to the SMTP Server: <hostname>:<portno>
servername := fmt.Sprintf("%s:%d", mc.Host, mc.PortNo)
auth := smtp.PlainAuth("", mc.UserName, mc.Password, mc.Host)
// create a connection first
c, err := smtp.Dial(servername)
if err != nil {
return err
}
if ok, _ := c.Extension("STARTTLS"); ok {
// TLS config
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: mc.Host}
c.StartTLS(tlsconfig)
}
// Autheticate
if err = c.Auth(auth); err != nil {
return err
}
// From (sender's email address)
if err = c.Mail(m.From.Address); err != nil {
return err
}
// Add all recipients using the same connection
// To
for i := 0; i < len(m.To); i++ {
// To enable DSN (Delivery Status Notification), see above comments...
// comment out the following func, and uncomment the above func;
if err = c.Rcpt(m.To[i].Address); err != nil {
return err
}
}
// CC
for i := 0; i < len(m.CC); i++ {
if err = c.Rcpt(m.CC[i].Address); err != nil {
return err
}
}
// BCC (not included in the header, which makes it not visible to recipients)
for i := 0; i < len(m.BCC); i++ {
if err = c.Rcpt(m.BCC[i].Address); err != nil {
return err
}
}
// get a writer for the Data
w, err := c.Data()
if err != nil {
return err
}
// write the bytes of the headers to the data writer.
if _, err = w.Write([]byte(msgHeaders)); err != nil {
return err
}
// close the writer (flush); this causes the email to be sent.
if err = w.Close(); err != nil {
return err
}
// close the connection
if err = c.Quit(); err != nil {
return err
}
return nil
}
func validate(m MailItem, mc MailCredentials) error {
if mc.Host == "" || mc.PortNo < 1 || mc.PortNo > 65535 || mc.UserName == "" ||
len(m.To) == 0 || !emailValid(m.From.Address) {
return errors.New("invalid settings")
}
if len(m.Language) > 5 {
return errors.New("invalid language")
}
if m.Priority > 0 && (m.Priority > 5) {
return errors.New("invalid priority")
}
return nil
}
// SendMail send multiple emails (to,cc, and bcc) to an smtp host.
func SendMail(m MailItem, mc MailCredentials) error {
if err := validate(m, mc); err != nil {
return err
}
// prepare the headers
msgHeaders := prepareHeaders(m)
// send the message
return sendMessage(m, mc, msgHeaders)
}