forked from wneessen/go-mail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
msgwriter.go
371 lines (332 loc) · 8.36 KB
/
msgwriter.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// SPDX-FileCopyrightText: 2022-2023 The go-mail Authors
//
// SPDX-License-Identifier: MIT
package mail
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"mime"
"mime/multipart"
"mime/quotedprintable"
"net/textproto"
"path/filepath"
"sort"
"strings"
)
// MaxHeaderLength defines the maximum line length for a mail header
// RFC 2047 suggests 76 characters
const MaxHeaderLength = 76
// MaxBodyLength defines the maximum line length for the mail body
// RFC 2047 suggests 76 characters
const MaxBodyLength = 76
// SingleNewLine represents a new line that can be used by the msgWriter to issue a carriage return
const SingleNewLine = "\r\n"
// DoubleNewLine represents a double new line that can be used by the msgWriter to
// indicate a new segement of the mail
const DoubleNewLine = "\r\n\r\n"
// msgWriter handles the I/O to the io.WriteCloser of the SMTP client
type msgWriter struct {
c Charset
d int8
en mime.WordEncoder
err error
mpw [3]*multipart.Writer
n int64
pw io.Writer
w io.Writer
}
// Write implements the io.Writer interface for msgWriter
func (mw *msgWriter) Write(p []byte) (int, error) {
if mw.err != nil {
return 0, fmt.Errorf("failed to write due to previous error: %w", mw.err)
}
var n int
n, mw.err = mw.w.Write(p)
mw.n += int64(n)
return n, mw.err
}
// writeMsg formats the message and sends it to its io.Writer
func (mw *msgWriter) writeMsg(m *Msg) {
m.addDefaultHeader()
m.checkUserAgent()
mw.writeGenHeader(m)
mw.writePreformattedGenHeader(m)
// Set the FROM header (or envelope FROM if FROM is empty)
hf := true
f, ok := m.addrHeader[HeaderFrom]
if !ok || len(f) == 0 {
f, ok = m.addrHeader[HeaderEnvelopeFrom]
if !ok || len(f) == 0 {
hf = false
}
}
if hf {
mw.writeHeader(Header(HeaderFrom), f[0].String())
}
// Set the rest of the address headers
for _, t := range []AddrHeader{HeaderTo, HeaderCc} {
if al, ok := m.addrHeader[t]; ok {
var v []string
for _, a := range al {
v = append(v, a.String())
}
mw.writeHeader(Header(t), v...)
}
}
if m.hasMixed() {
mw.startMP("mixed", m.boundary)
mw.writeString(DoubleNewLine)
}
if m.hasRelated() {
mw.startMP("related", m.boundary)
mw.writeString(DoubleNewLine)
}
if m.hasAlt() {
mw.startMP(MIMEAlternative, m.boundary)
mw.writeString(DoubleNewLine)
}
if m.hasPGPType() {
switch m.pgptype {
case PGPEncrypt:
mw.startMP(`encrypted; protocol="application/pgp-encrypted"`, m.boundary)
case PGPSignature:
mw.startMP(`signed; protocol="application/pgp-signature";`, m.boundary)
}
mw.writeString(DoubleNewLine)
}
for _, p := range m.parts {
if !p.del {
mw.writePart(p, m.charset)
}
}
if m.hasAlt() {
mw.stopMP()
}
// Add embeds
mw.addFiles(m.embeds, false)
if m.hasRelated() {
mw.stopMP()
}
// Add attachments
mw.addFiles(m.attachments, true)
if m.hasMixed() {
mw.stopMP()
}
}
// writeGenHeader writes out all generic headers to the msgWriter
func (mw *msgWriter) writeGenHeader(m *Msg) {
gk := make([]string, 0, len(m.genHeader))
for k := range m.genHeader {
gk = append(gk, string(k))
}
sort.Strings(gk)
for _, k := range gk {
mw.writeHeader(Header(k), m.genHeader[Header(k)]...)
}
}
// writePreformatedHeader writes out all preformated generic headers to the msgWriter
func (mw *msgWriter) writePreformattedGenHeader(m *Msg) {
for k, v := range m.preformHeader {
mw.writeString(fmt.Sprintf("%s: %s%s", k, v, SingleNewLine))
}
}
// startMP writes a multipart beginning
func (mw *msgWriter) startMP(mt MIMEType, b string) {
mp := multipart.NewWriter(mw)
if b != "" {
mw.err = mp.SetBoundary(b)
}
ct := fmt.Sprintf("multipart/%s;\r\n boundary=%s", mt, mp.Boundary())
mw.mpw[mw.d] = mp
if mw.d == 0 {
mw.writeString(fmt.Sprintf("%s: %s", HeaderContentType, ct))
}
if mw.d > 0 {
mw.newPart(map[string][]string{"Content-Type": {ct}})
}
mw.d++
}
// stopMP closes the multipart
func (mw *msgWriter) stopMP() {
if mw.d > 0 {
mw.err = mw.mpw[mw.d-1].Close()
mw.d--
}
}
// addFiles adds the attachments/embeds file content to the mail body
func (mw *msgWriter) addFiles(fl []*File, a bool) {
for _, f := range fl {
e := EncodingB64
if _, ok := f.getHeader(HeaderContentType); !ok {
mt := mime.TypeByExtension(filepath.Ext(f.Name))
if mt == "" {
mt = "application/octet-stream"
}
if f.ContentType != "" {
mt = string(f.ContentType)
}
f.setHeader(HeaderContentType, fmt.Sprintf(`%s; name="%s"`, mt,
mw.en.Encode(mw.c.String(), f.Name)))
}
if _, ok := f.getHeader(HeaderContentTransferEnc); !ok {
if f.Enc != "" {
e = f.Enc
}
f.setHeader(HeaderContentTransferEnc, string(e))
}
if f.Desc != "" {
if _, ok := f.getHeader(HeaderContentDescription); !ok {
f.setHeader(HeaderContentDescription, f.Desc)
}
}
if _, ok := f.getHeader(HeaderContentDisposition); !ok {
d := "inline"
if a {
d = "attachment"
}
f.setHeader(HeaderContentDisposition, fmt.Sprintf(`%s; filename="%s"`, d,
mw.en.Encode(mw.c.String(), f.Name)))
}
if !a {
if _, ok := f.getHeader(HeaderContentID); !ok {
f.setHeader(HeaderContentID, fmt.Sprintf("<%s>", f.Name))
}
}
if mw.d == 0 {
for h, v := range f.Header {
mw.writeHeader(Header(h), v...)
}
mw.writeString(SingleNewLine)
}
if mw.d > 0 {
mw.newPart(f.Header)
}
if mw.err == nil {
mw.writeBody(f.Writer, e)
}
}
}
// newPart creates a new MIME multipart io.Writer and sets the partwriter to it
func (mw *msgWriter) newPart(h map[string][]string) {
mw.pw, mw.err = mw.mpw[mw.d-1].CreatePart(h)
}
// writePart writes the corresponding part to the Msg body
func (mw *msgWriter) writePart(p *Part, cs Charset) {
ct := fmt.Sprintf("%s; charset=%s", p.ctype, cs)
cte := p.enc.String()
if mw.d == 0 {
mw.writeHeader(HeaderContentType, ct)
mw.writeHeader(HeaderContentTransferEnc, cte)
mw.writeString(SingleNewLine)
}
if mw.d > 0 {
mh := textproto.MIMEHeader{}
if p.desc != "" {
mh.Add(string(HeaderContentDescription), p.desc)
}
mh.Add(string(HeaderContentType), ct)
mh.Add(string(HeaderContentTransferEnc), cte)
mw.newPart(mh)
}
mw.writeBody(p.w, p.enc)
}
// writeString writes a string into the msgWriter's io.Writer interface
func (mw *msgWriter) writeString(s string) {
if mw.err != nil {
return
}
var n int
n, mw.err = io.WriteString(mw.w, s)
mw.n += int64(n)
}
// writeHeader writes a header into the msgWriter's io.Writer
func (mw *msgWriter) writeHeader(k Header, vl ...string) {
wbuf := bytes.Buffer{}
cl := MaxHeaderLength - 2
wbuf.WriteString(string(k))
cl -= len(k)
if len(vl) == 0 {
wbuf.WriteString(":\r\n")
return
}
wbuf.WriteString(": ")
cl -= 2
fs := strings.Join(vl, ", ")
sfs := strings.Split(fs, " ")
for i, v := range sfs {
if cl-len(v) <= 1 {
wbuf.WriteString(fmt.Sprintf("%s ", SingleNewLine))
cl = MaxHeaderLength - 3
}
wbuf.WriteString(v)
if i < len(sfs)-1 {
wbuf.WriteString(" ")
cl -= 1
}
cl -= len(v)
}
bufs := wbuf.String()
bufs = strings.ReplaceAll(bufs, fmt.Sprintf(" %s", SingleNewLine), SingleNewLine)
mw.writeString(bufs)
mw.writeString("\r\n")
}
// writeBody writes an io.Reader into an io.Writer using provided Encoding
func (mw *msgWriter) writeBody(f func(io.Writer) (int64, error), e Encoding) {
var w io.Writer
var ew io.WriteCloser
var n int64
var err error
if mw.d == 0 {
w = mw.w
}
if mw.d > 0 {
w = mw.pw
}
wbuf := bytes.Buffer{}
lb := Base64LineBreaker{}
lb.out = &wbuf
switch e {
case EncodingQP:
ew = quotedprintable.NewWriter(&wbuf)
case EncodingB64:
ew = base64.NewEncoder(base64.StdEncoding, &lb)
case NoEncoding:
_, err = f(&wbuf)
if err != nil {
mw.err = fmt.Errorf("bodyWriter function: %w", err)
}
n, err = io.Copy(w, &wbuf)
if err != nil && mw.err == nil {
mw.err = fmt.Errorf("bodyWriter io.Copy: %w", err)
}
if mw.d == 0 {
mw.n += n
}
return
default:
ew = quotedprintable.NewWriter(w)
}
_, err = f(ew)
if err != nil {
mw.err = fmt.Errorf("bodyWriter function: %w", err)
}
err = ew.Close()
if err != nil && mw.err == nil {
mw.err = fmt.Errorf("bodyWriter close encoded writer: %w", err)
}
err = lb.Close()
if err != nil && mw.err == nil {
mw.err = fmt.Errorf("bodyWriter close linebreaker: %w", err)
}
n, err = io.Copy(w, &wbuf)
if err != nil && mw.err == nil {
mw.err = fmt.Errorf("bodyWriter io.Copy: %w", err)
}
// Since the part writer uses the WriteTo() method, we don't need to add the
// bytes twice
if mw.d == 0 {
mw.n += n
}
}