forked from jpoehls/gophermail
/
main.go
352 lines (284 loc) · 8.73 KB
/
main.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
package gophermail
import (
"bytes"
"errors"
"fmt"
//"github.com/sloonz/go-qprintable"
"io"
"mime"
"mime/multipart"
"net/mail"
"net/textproto"
"path/filepath"
)
// Message Lint: http://tools.ietf.org/tools/msglint/
const crlf = "\r\n"
var ErrMissingRecipient = errors.New("No recipient specified. At one To, Cc, or Bcc recipient is required.")
var ErrMissingFromAddress = errors.New("No from address specified.")
// A Message represents an email message.
// Addresses may be of any form permitted by RFC 5322.
type Message struct {
// TODO(JPOEHLS): Add support for specifying the Sender header.
// Technically this could be a list of addresses but we don't support that. See RFC 2822 s3.6.2.
From string
// Technically this could be a list of addresses but we don't support that. See RFC 2822 s3.6.2.
ReplyTo string // optional
// At least one of these slices must have a non-zero length.
To, Cc, Bcc []string
Subject string // optional
Body string // optional
HTMLBody string // optional
Attachments []Attachment // optional
// TODO(JPOEHLS): Support extra mail headers? Things like On-Behalf-Of, In-Reply-To, List-Unsubscribe, etc.
}
// An Attachment represents an email attachment.
type Attachment struct {
// Name must be set to a valid file name.
Name string
// Optional.
// Uses mime.TypeByExtension and falls back
// to application/octet-stream if unknown.
ContentType string
Data io.Reader
}
// Bytes gets the encoded MIME message.
func (m *Message) Bytes() ([]byte, error) {
var buffer = &bytes.Buffer{}
header := textproto.MIMEHeader{}
// Require To, Cc, or Bcc
var hasTo = m.To != nil && len(m.To) > 0
var hasCc = m.Cc != nil && len(m.Cc) > 0
var hasBcc = m.Bcc != nil && len(m.Bcc) > 0
if !hasTo && !hasCc && !hasBcc {
return nil, ErrMissingRecipient
} else {
if hasTo {
toAddrs, err := getAddressListString(m.To)
if err != nil {
return nil, err
}
header.Add("To", toAddrs)
}
if hasCc {
ccAddrs, err := getAddressListString(m.Cc)
if err != nil {
return nil, err
}
header.Add("Cc", ccAddrs)
}
}
// Require From address
if m.From == "" {
return nil, ErrMissingFromAddress
} else {
parsedAddy, err := mail.ParseAddress(m.From)
if err != nil {
return nil, err
}
header.Add("From", parsedAddy.String())
}
// Optional ReplyTo
if m.ReplyTo != "" {
parsedAddy, err := mail.ParseAddress(m.ReplyTo)
if err != nil {
return nil, err
}
header.Add("Reply-To", parsedAddy.String())
}
// Optional Subject
if m.Subject != "" {
header.Add("Subject", qEncodeAndWrap(m.Subject, 9 /* len("Subject: ") */))
}
// Top level multipart writer for our `multipart/mixed` body.
mixedw := multipart.NewWriter(buffer)
var err error
header.Add("MIME-Version", "1.0")
header.Add("Content-Type", fmt.Sprintf("multipart/mixed;%s boundary=%s", crlf, mixedw.Boundary()))
err = writeHeader(buffer, header)
if err != nil {
return nil, err
}
// Write the start of our `multipart/mixed` body.
_, err = fmt.Fprintf(buffer, "--%s%s", mixedw.Boundary(), crlf)
if err != nil {
return nil, err
}
// Does the message have a body?
if m.Body != "" || m.HTMLBody != "" {
// Nested multipart writer for our `multipart/alternative` body.
altw := multipart.NewWriter(buffer)
header = textproto.MIMEHeader{}
header.Add("Content-Type", fmt.Sprintf("multipart/alternative;%s boundary=%s", crlf, altw.Boundary()))
err := writeHeader(buffer, header)
if err != nil {
return nil, err
}
if m.Body != "" {
header = textproto.MIMEHeader{}
header.Add("Content-Type", "text/plain; charset=utf-8")
//header.Add("Content-Transfer-Encoding", "quoted-printable")
header.Add("Content-Transfer-Encoding", "base64")
partw, err := altw.CreatePart(header)
if err != nil {
return nil, err
}
bodyBytes := []byte(m.Body)
encoder := NewBase64MimeEncoder(partw)
//encoder := qprintable.NewEncoder(qprintable.DetectEncoding(m.Body), partw)
_, err = encoder.Write(bodyBytes)
if err != nil {
return nil, err
}
err = encoder.Close()
if err != nil {
return nil, err
}
}
if m.HTMLBody != "" {
header = textproto.MIMEHeader{}
header.Add("Content-Type", "text/html; charset=utf-8")
//header.Add("Content-Transfer-Encoding", "quoted-printable")
header.Add("Content-Transfer-Encoding", "base64")
partw, err := altw.CreatePart(header)
if err != nil {
return nil, err
}
htmlBodyBytes := []byte(m.HTMLBody)
encoder := NewBase64MimeEncoder(partw)
//encoder := qprintable.NewEncoder(qprintable.DetectEncoding(m.HTMLBody), partw)
_, err = encoder.Write(htmlBodyBytes)
if err != nil {
return nil, err
}
err = encoder.Close()
if err != nil {
return nil, err
}
}
altw.Close()
}
if m.Attachments != nil && len(m.Attachments) > 0 {
for _, attachment := range m.Attachments {
contentType := attachment.ContentType
if contentType == "" {
contentType = mime.TypeByExtension(filepath.Ext(attachment.Name))
if contentType == "" {
contentType = "application/octet-stream"
}
}
header := textproto.MIMEHeader{}
header.Add("Content-Type", contentType)
header.Add("Content-Disposition", fmt.Sprintf(`attachment;%s filename="%s"`, crlf, attachment.Name))
header.Add("Content-Transfer-Encoding", "base64")
attachmentPart, err := mixedw.CreatePart(header)
if err != nil {
return nil, err
}
encoder := NewBase64MimeEncoder(attachmentPart)
_, err = io.Copy(encoder, attachment.Data)
if err != nil {
return nil, err
}
err = encoder.Close()
if err != nil {
return nil, err
}
}
}
mixedw.Close()
return buffer.Bytes(), nil
}
// writeHeader writes the specified MIMEHeader to the io.Writer.
// Header values will be trimmed but otherwise left alone.
// Headers with multiple values are not supported and will return an error.
func writeHeader(w io.Writer, header textproto.MIMEHeader) error {
for k, vs := range header {
_, err := fmt.Fprintf(w, "%s: ", k)
if err != nil {
return err
}
for i, v := range vs {
v = textproto.TrimString(v)
_, err := fmt.Fprintf(w, "%s", v)
if err != nil {
return err
}
if i < len(vs)-1 {
return errors.New("Multiple header values are not supported.")
}
}
_, err = fmt.Fprint(w, crlf)
if err != nil {
return err
}
}
// Write a blank line as a spacer
_, err := fmt.Fprint(w, crlf)
if err != nil {
return err
}
return nil
}
// qEncode encodes a string with Q encoding defined as an 'encoded-word' in RFC 2047.
// The maximum encoded word length of 75 characters is not accounted for.
// Use qEncodeAndWrap if you need that.
//
// Inspired by https://gist.github.com/andelf/5004821
func qEncode(input string) string {
// use mail's rfc2047 to encode any string
addr := mail.Address{input, ""}
s := addr.String()
return s[:len(s)-3]
}
// qEncodeAndWrap encodes the input as potentially multiple 'encoded-words'
// with CRLF SPACE line breaks between them to (as best as possible)
// guarantee that each encoded-word is no more than 75 characters
// and, padding included, each line is no longer than 76 characters.
// See RFC 2047 s2.
func qEncodeAndWrap(input string, padding int) string {
// Increase the padding to account for
// the encoded-word 'envelop' tokens.
// "?" charset (utf-8 is always assumed) "?" encoding "?" encoded-text "?="
padding += 11
// Tokenization included, the encoded word must not
// be longer than 75 characters.
const maxEncodedWordLength = 75
var firstTry = qEncode(input)
if len(firstTry) > maxEncodedWordLength-padding {
// TODO(JPOEHLS): Implement an algorithm to break the input into multiple encoded-words.
return firstTry
} else {
return firstTry
}
}
// getAddressListString encodes a slice of email addresses into
// a string value suitable for a MIME header. Each address is
// Q encoded and wrapped onto its own line to help ensure that
// the header line doesn't cross the 78 character maximum.
func getAddressListString(addresses []string) (string, error) {
buffer := bytes.NewBuffer([]byte{})
for i, v := range addresses {
parsedAddy, err := mail.ParseAddress(v)
if err != nil {
return "", err
}
_, err = fmt.Fprint(buffer, parsedAddy.String())
if err != nil {
return "", err
}
// TODO(ANYONE): Currently we are splitting each address onto its own line
// because this is the easiest way to ensure lines don't exceed
// the max length. Ideally we wouldn't split until we actually
// needed to.
// Separate multiple addresses with a comma
// and wrap them to their own line using whitespace folding.
// See RFC 2822 s2.2.3.
if i < len(addresses)-1 {
_, err := fmt.Fprint(buffer, ","+crlf+" ")
if err != nil {
return "", err
}
}
}
return buffer.String(), nil
}