| 1 |
package enmime |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"io" |
| 6 |
"mime" |
| 7 |
"net/mail" |
| 8 |
"net/textproto" |
| 9 |
"strings" |
| 10 |
|
| •11 |
"jaytaylor.com/html2text" |
| 12 |
"github.com/jhillyerd/enmime/internal/coding" |
| 13 |
"github.com/jhillyerd/enmime/mediatype" |
| 14 |
"github.com/pkg/errors" |
| 15 |
) |
| 16 |
|
| 17 |
// Envelope is a simplified wrapper for MIME email messages. |
| 18 |
type Envelope struct { |
| 19 |
Text string // The plain text portion of the message |
| 20 |
HTML string // The HTML portion of the message |
| 21 |
Root *Part // The top-level Part |
| 22 |
Attachments []*Part // All parts having a Content-Disposition of attachment |
| 23 |
Inlines []*Part // All parts having a Content-Disposition of inline |
| 24 |
// All non-text parts that were not placed in Attachments or Inlines, such as multipart/related |
| 25 |
// content. |
| 26 |
OtherParts []*Part |
| 27 |
Errors []*Error // Errors encountered while parsing |
| 28 |
header *textproto.MIMEHeader // Header from original message |
| 29 |
} |
| 30 |
|
| 31 |
// GetHeaderKeys returns a list of header keys seen in this message. Get |
| 32 |
// individual headers with `GetHeader(name)` |
| 33 |
func (e *Envelope) GetHeaderKeys() (headers []string) { |
| 34 |
if e.header == nil { |
| 35 |
return |
| 36 |
} |
| 37 |
for key := range *e.header { |
| 38 |
headers = append(headers, key) |
| 39 |
} |
| 40 |
return headers |
| 41 |
} |
| 42 |
|
| 43 |
// GetHeader processes the specified header for RFC 2047 encoded words and returns the result as a |
| 44 |
// UTF-8 string |
| 45 |
func (e *Envelope) GetHeader(name string) string { |
| 46 |
if e.header == nil { |
| 47 |
return "" |
| 48 |
} |
| 49 |
return coding.DecodeExtHeader(e.header.Get(name)) |
| 50 |
} |
| 51 |
|
| 52 |
// GetHeaderValues processes the specified header for RFC 2047 encoded words and returns all existing |
| 53 |
// values as a list of UTF-8 strings |
| 54 |
func (e *Envelope) GetHeaderValues(name string) []string { |
| 55 |
if e.header == nil { |
| 56 |
return []string{} |
| 57 |
} |
| 58 |
|
| 59 |
rawValues := (*e.header)[textproto.CanonicalMIMEHeaderKey(name)] |
| 60 |
var values []string |
| 61 |
for _, v := range rawValues { |
| 62 |
values = append(values, coding.DecodeExtHeader(v)) |
| 63 |
} |
| 64 |
return values |
| 65 |
} |
| 66 |
|
| 67 |
// SetHeader sets given header name to the given value. |
| 68 |
// If the header exists already, all existing values are replaced. |
| 69 |
func (e *Envelope) SetHeader(name string, value []string) error { |
| 70 |
if name == "" { |
| 71 |
return fmt.Errorf("provide non-empty header name") |
| 72 |
} |
| 73 |
|
| 74 |
for i, v := range value { |
| 75 |
if i == 0 { |
| 76 |
e.header.Set(name, mime.BEncoding.Encode("utf-8", v)) |
| 77 |
continue |
| 78 |
} |
| 79 |
e.header.Add(name, mime.BEncoding.Encode("utf-8", v)) |
| 80 |
} |
| 81 |
return nil |
| 82 |
} |
| 83 |
|
| 84 |
// AddHeader appends given header value to header name without changing existing values. |
| 85 |
// If the header does not exist already, it will be created. |
| 86 |
func (e *Envelope) AddHeader(name string, value string) error { |
| 87 |
if name == "" { |
| 88 |
return fmt.Errorf("provide non-empty header name") |
| 89 |
} |
| 90 |
|
| 91 |
e.header.Add(name, mime.BEncoding.Encode("utf-8", value)) |
| 92 |
return nil |
| 93 |
} |
| 94 |
|
| 95 |
// DeleteHeader deletes given header. |
| 96 |
func (e *Envelope) DeleteHeader(name string) error { |
| 97 |
if name == "" { |
| 98 |
return fmt.Errorf("provide non-empty header name") |
| 99 |
} |
| 100 |
|
| 101 |
e.header.Del(name) |
| 102 |
return nil |
| 103 |
} |
| 104 |
|
| 105 |
// AddressList returns a mail.Address slice with RFC 2047 encoded names converted to UTF-8 |
| 106 |
func (e *Envelope) AddressList(key string) ([]*mail.Address, error) { |
| 107 |
if e.header == nil { |
| 108 |
return nil, fmt.Errorf("no headers available") |
| 109 |
} |
| 110 |
if !AddressHeaders[strings.ToLower(key)] { |
| 111 |
return nil, fmt.Errorf("%s is not an address header", key) |
| 112 |
} |
| 113 |
|
| 114 |
str := decodeToUTF8Base64Header(e.header.Get(key)) |
| 115 |
|
| 116 |
// These statements are handy for debugging ParseAddressList errors |
| 117 |
// fmt.Println("in: ", m.header.Get(key)) |
| 118 |
// fmt.Println("out: ", str) |
| 119 |
ret, err := mail.ParseAddressList(str) |
| 120 |
if err != nil { |
| 121 |
switch err.Error() { |
| 122 |
case "mail: expected comma": |
| 123 |
return mail.ParseAddressList(ensureCommaDelimitedAddresses(str)) |
| 124 |
case "mail: no address": |
| 125 |
return nil, mail.ErrHeaderNotPresent |
| 126 |
} |
| 127 |
return nil, err |
| 128 |
} |
| 129 |
return ret, nil |
| 130 |
} |
| 131 |
|
| 132 |
// Clone returns a clone of the current Envelope |
| 133 |
func (e *Envelope) Clone() *Envelope { |
| 134 |
if e == nil { |
| 135 |
return nil |
| 136 |
} |
| 137 |
|
| 138 |
newEnvelope := &Envelope{ |
| 139 |
e.Text, |
| 140 |
e.HTML, |
| 141 |
e.Root.Clone(nil), |
| 142 |
e.Attachments, |
| 143 |
e.Inlines, |
| 144 |
e.OtherParts, |
| 145 |
e.Errors, |
| 146 |
e.header, |
| 147 |
} |
| 148 |
return newEnvelope |
| 149 |
} |
| 150 |
|
| 151 |
// ReadEnvelope is a wrapper around ReadParts and EnvelopeFromPart. It parses the content of the |
| 152 |
// provided reader into an Envelope, downconverting HTML to plain text if needed, and sorting the |
| 153 |
// attachments, inlines and other parts into their respective slices. Errors are collected from all |
| 154 |
// Parts and placed into the Envelope.Errors slice. |
| 155 |
func ReadEnvelope(r io.Reader) (*Envelope, error) { |
| 156 |
// Read MIME parts from reader |
| 157 |
root, err := ReadParts(r) |
| 158 |
if err != nil { |
| 159 |
return nil, errors.WithMessage(err, "Failed to ReadParts") |
| 160 |
} |
| 161 |
return EnvelopeFromPart(root) |
| 162 |
} |
| 163 |
|
| 164 |
// EnvelopeFromPart uses the provided Part tree to build an Envelope, downconverting HTML to plain |
| 165 |
// text if needed, and sorting the attachments, inlines and other parts into their respective |
| 166 |
// slices. Errors are collected from all Parts and placed into the Envelopes Errors slice. |
| 167 |
func EnvelopeFromPart(root *Part) (*Envelope, error) { |
| 168 |
e := &Envelope{ |
| 169 |
Root: root, |
| 170 |
header: &root.Header, |
| 171 |
} |
| 172 |
|
| 173 |
if detectMultipartMessage(root) { |
| 174 |
// Multi-part message (message with attachments, etc) |
| 175 |
if err := parseMultiPartBody(root, e); err != nil { |
| 176 |
return nil, err |
| 177 |
} |
| 178 |
} else { |
| 179 |
if detectBinaryBody(root) { |
| 180 |
// Attachment only, no text |
| 181 |
if root.Disposition == cdInline { |
| 182 |
e.Inlines = append(e.Inlines, root) |
| 183 |
} else { |
| 184 |
e.Attachments = append(e.Attachments, root) |
| 185 |
} |
| 186 |
} else { |
| 187 |
// Only text, no attachments |
| 188 |
if err := parseTextOnlyBody(root, e); err != nil { |
| 189 |
return nil, err |
| 190 |
} |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
// Down-convert HTML to text if necessary |
| 195 |
if e.Text == "" && e.HTML != "" { |
| 196 |
// We always warn when this happens |
| 197 |
e.Root.addWarning( |
| 198 |
ErrorPlainTextFromHTML, |
| 199 |
"Message did not contain a text/plain part") |
| 200 |
var err error |
| 201 |
if e.Text, err = html2text.FromString(e.HTML); err != nil { |
| 202 |
e.Text = "" // Down-conversion shouldn't fail |
| 203 |
p := e.Root.BreadthMatchFirst(matchHTMLBodyPart) |
| 204 |
p.addError(ErrorPlainTextFromHTML, "Failed to downconvert HTML: %v", err) |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
// Copy part errors into Envelope. |
| 209 |
if e.Root != nil { |
| 210 |
_ = e.Root.DepthMatchAll(func(part *Part) bool { |
| 211 |
// Using DepthMatchAll to traverse all parts, don't care about result. |
| 212 |
for i := range part.Errors { |
| 213 |
// Range index is needed to get the correct address, because range value points to |
| 214 |
// a locally scoped variable. |
| 215 |
e.Errors = append(e.Errors, part.Errors[i]) |
| 216 |
} |
| 217 |
return false |
| 218 |
}) |
| 219 |
} |
| 220 |
|
| 221 |
return e, nil |
| 222 |
} |
| 223 |
|
| 224 |
// parseTextOnlyBody parses a plain text message in root that has MIME-like headers, but |
| 225 |
// only contains a single part - no boundaries, etc. The result is placed in e. |
| 226 |
func parseTextOnlyBody(root *Part, e *Envelope) error { |
| 227 |
// Determine character set |
| 228 |
var charset string |
| 229 |
var isHTML bool |
| 230 |
if ctype := root.Header.Get(hnContentType); ctype != "" { |
| 231 |
if mediatype, mparams, _, err := mediatype.Parse(ctype); err == nil { |
| 232 |
isHTML = (mediatype == ctTextHTML) |
| 233 |
if mparams[hpCharset] != "" { |
| 234 |
charset = mparams[hpCharset] |
| 235 |
} |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
// Read transcoded text |
| 240 |
if isHTML { |
| 241 |
rawHTML := string(root.Content) |
| 242 |
// Note: Empty e.Text will trigger html2text conversion |
| 243 |
e.HTML = rawHTML |
| 244 |
if charset == "" { |
| 245 |
// Search for charset in HTML metadata |
| 246 |
if charset = coding.FindCharsetInHTML(rawHTML); charset != "" { |
| 247 |
// Found charset in HTML |
| 248 |
if convHTML, err := coding.ConvertToUTF8String(charset, root.Content); err == nil { |
| 249 |
// Successful conversion |
| 250 |
e.HTML = convHTML |
| 251 |
} else { |
| 252 |
// Conversion failed |
| 253 |
root.addWarning(ErrorCharsetConversion, err.Error()) |
| 254 |
} |
| 255 |
} |
| 256 |
// Converted from charset in HTML |
| 257 |
return nil |
| 258 |
} |
| 259 |
} else { |
| 260 |
e.Text = string(root.Content) |
| 261 |
} |
| 262 |
|
| 263 |
return nil |
| 264 |
} |
| 265 |
|
| 266 |
// parseMultiPartBody parses a multipart message in root. The result is placed in e. |
| 267 |
func parseMultiPartBody(root *Part, e *Envelope) error { |
| 268 |
// Parse top-level multipart |
| 269 |
ctype := root.Header.Get(hnContentType) |
| 270 |
mediatype, params, _, err := mediatype.Parse(ctype) |
| 271 |
if err != nil { |
| 272 |
return fmt.Errorf("unable to parse media type: %v", err) |
| 273 |
} |
| 274 |
if !strings.HasPrefix(mediatype, ctMultipartPrefix) { |
| 275 |
return fmt.Errorf("unknown mediatype: %v", mediatype) |
| 276 |
} |
| 277 |
boundary := params[hpBoundary] |
| 278 |
if boundary == "" { |
| 279 |
return fmt.Errorf("unable to locate boundary param in Content-Type header") |
| 280 |
} |
| 281 |
|
| 282 |
// Locate text body |
| 283 |
if mediatype == ctMultipartAltern { |
| 284 |
p := root.BreadthMatchFirst(func(p *Part) bool { |
| 285 |
return p.ContentType == ctTextPlain && p.Disposition != cdAttachment |
| 286 |
}) |
| 287 |
if p != nil { |
| 288 |
e.Text = string(p.Content) |
| 289 |
} |
| 290 |
} else { |
| 291 |
// multipart is of a mixed type |
| 292 |
parts := root.DepthMatchAll(func(p *Part) bool { |
| 293 |
return p.ContentType == ctTextPlain && p.Disposition != cdAttachment |
| 294 |
}) |
| 295 |
for i, p := range parts { |
| 296 |
if i > 0 { |
| 297 |
e.Text += "\n--\n" |
| 298 |
} |
| 299 |
e.Text += string(p.Content) |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
// Locate HTML body |
| 304 |
p := root.DepthMatchFirst(matchHTMLBodyPart) |
| 305 |
if p != nil { |
| 306 |
e.HTML += string(p.Content) |
| 307 |
} |
| 308 |
|
| 309 |
// Locate attachments |
| 310 |
e.Attachments = root.BreadthMatchAll(func(p *Part) bool { |
| 311 |
return p.Disposition == cdAttachment || p.ContentType == ctAppOctetStream |
| 312 |
}) |
| 313 |
|
| 314 |
// Locate inlines |
| 315 |
e.Inlines = root.BreadthMatchAll(func(p *Part) bool { |
| 316 |
return p.Disposition == cdInline && !strings.HasPrefix(p.ContentType, ctMultipartPrefix) |
| 317 |
}) |
| 318 |
|
| 319 |
// Locate others parts not considered in attachments or inlines |
| 320 |
e.OtherParts = root.BreadthMatchAll(func(p *Part) bool { |
| 321 |
if strings.HasPrefix(p.ContentType, ctMultipartPrefix) { |
| 322 |
return false |
| 323 |
} |
| 324 |
if p.Disposition != "" { |
| 325 |
return false |
| 326 |
} |
| 327 |
if p.ContentType == ctAppOctetStream { |
| 328 |
return false |
| 329 |
} |
| 330 |
return p.ContentType != ctTextPlain && p.ContentType != ctTextHTML |
| 331 |
}) |
| 332 |
|
| 333 |
return nil |
| 334 |
} |
| 335 |
|
| 336 |
// Used by Part matchers to locate the HTML body. Not inlined because it's used in multiple places. |
| 337 |
func matchHTMLBodyPart(p *Part) bool { |
| 338 |
return p.ContentType == ctTextHTML && p.Disposition != cdAttachment |
| 339 |
} |
| 340 |
|
| 341 |
// Used by AddressList to ensure that address lists are properly delimited |
| 342 |
func ensureCommaDelimitedAddresses(s string) string { |
| 343 |
// This normalizes the whitespace, but may interfere with CFWS (comments with folding whitespace) |
| 344 |
// RFC-5322 3.4.0: |
| 345 |
// because some legacy implementations interpret the comment, |
| 346 |
// comments generally SHOULD NOT be used in address fields |
| 347 |
// to avoid confusing such implementations. |
| 348 |
s = strings.Join(strings.Fields(s), " ") |
| 349 |
|
| 350 |
inQuotes := false |
| 351 |
inDomain := false |
| 352 |
escapeSequence := false |
| 353 |
sb := strings.Builder{} |
| 354 |
for _, r := range s { |
| 355 |
if escapeSequence { |
| 356 |
escapeSequence = false |
| 357 |
sb.WriteRune(r) |
| 358 |
continue |
| 359 |
} |
| 360 |
if r == '"' { |
| 361 |
inQuotes = !inQuotes |
| 362 |
sb.WriteRune(r) |
| 363 |
continue |
| 364 |
} |
| 365 |
if inQuotes { |
| 366 |
if r == '\\' { |
| 367 |
escapeSequence = true |
| 368 |
sb.WriteRune(r) |
| 369 |
continue |
| 370 |
} |
| 371 |
} else { |
| 372 |
if r == '@' { |
| 373 |
inDomain = true |
| 374 |
sb.WriteRune(r) |
| 375 |
continue |
| 376 |
} |
| 377 |
if inDomain { |
| 378 |
if r == ';' { |
| 379 |
sb.WriteRune(r) |
| 380 |
break |
| 381 |
} |
| 382 |
if r == ',' { |
| 383 |
inDomain = false |
| 384 |
sb.WriteRune(r) |
| 385 |
continue |
| 386 |
} |
| 387 |
if r == ' ' { |
| 388 |
inDomain = false |
| 389 |
sb.WriteRune(',') |
| 390 |
sb.WriteRune(r) |
| 391 |
continue |
| 392 |
} |
| 393 |
} |
| 394 |
} |
| 395 |
sb.WriteRune(r) |
| 396 |
} |
| 397 |
return sb.String() |
| 398 |
} |