Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
()
| 376 | |
| 377 | // Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc. |
| 378 | func (e *Email) Bytes() ([]byte, error) { |
| 379 | // TODO: better guess buffer size |
| 380 | buff := bytes.NewBuffer(make([]byte, 0, 4096)) |
| 381 | |
| 382 | headers, err := e.msgHeaders() |
| 383 | if err != nil { |
| 384 | return nil, err |
| 385 | } |
| 386 | |
| 387 | htmlAttachments, otherAttachments := e.categorizeAttachments() |
| 388 | if len(e.HTML) == 0 && len(htmlAttachments) > 0 { |
| 389 | return nil, errors.New("there are HTML attachments, but no HTML body") |
| 390 | } |
| 391 | |
| 392 | var ( |
| 393 | isMixed = len(otherAttachments) > 0 |
| 394 | isAlternative = len(e.Text) > 0 && len(e.HTML) > 0 |
| 395 | ) |
| 396 | |
| 397 | var w *multipart.Writer |
| 398 | if isMixed || isAlternative { |
| 399 | w = multipart.NewWriter(buff) |
| 400 | } |
| 401 | switch { |
| 402 | case isMixed: |
| 403 | headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary()) |
| 404 | case isAlternative: |
| 405 | headers.Set("Content-Type", "multipart/alternative;\r\n boundary="+w.Boundary()) |
| 406 | case len(e.HTML) > 0: |
| 407 | headers.Set("Content-Type", "text/html; charset=UTF-8") |
| 408 | headers.Set("Content-Transfer-Encoding", "quoted-printable") |
| 409 | default: |
| 410 | headers.Set("Content-Type", "text/plain; charset=UTF-8") |
| 411 | headers.Set("Content-Transfer-Encoding", "quoted-printable") |
| 412 | } |
| 413 | headerToBytes(buff, headers) |
| 414 | _, err = io.WriteString(buff, "\r\n") |
| 415 | if err != nil { |
| 416 | return nil, err |
| 417 | } |
| 418 | |
| 419 | // Check to see if there is a Text or HTML field |
| 420 | if len(e.Text) > 0 || len(e.HTML) > 0 { |
| 421 | var subWriter *multipart.Writer |
| 422 | |
| 423 | if isMixed && isAlternative { |
| 424 | // Create the multipart alternative part |
| 425 | subWriter = multipart.NewWriter(buff) |
| 426 | header := textproto.MIMEHeader{ |
| 427 | "Content-Type": {"multipart/alternative;\r\n boundary=" + subWriter.Boundary()}, |
| 428 | } |
| 429 | if _, err := w.CreatePart(header); err != nil { |
| 430 | return nil, err |
| 431 | } |
| 432 | } else { |
| 433 | subWriter = w |
| 434 | } |
| 435 | // Create the body sections |