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
package main

// Turning a draft into a message.
//
// A draft is an ordered list of typed blocks; a mail is bytes. This is the
// conversion, and the shape it produces is derived from the blocks rather than
// chosen by anybody:
//
//	text and quote only   → text/plain
//	code or image present → multipart/alternative { text/plain, text/html }
//	files attached        → multipart/mixed { <either of the above>, file* }
//
// The first rule is not about capability but about damage. Plain text is
// exactly what prose and quotations are for, and a mail client renders them the
// way every mail client has for thirty years. A code listing is different in
// kind: its meaning is in its whitespace, and a plain-text mail on the wire is
// subject to being rewrapped by anything between here and the reader. An image
// is not text at all. So the presence of either is what makes the *body* MIME,
// and nothing else does.
//
// The second is a different question and composes with the first rather than
// replacing it. mixed means "several things are enclosed", which is exactly
// true of a message with attachments and exactly false of one that is a single
// body in two renderings — which is why an alternative is not wrapped in a
// mixed when nothing is attached, and is when something is. A draft of prose
// with six photos therefore sends its prose as text/plain, inside a mixed:
// attaching a file does not make the body HTML, because it does nothing to the
// body at all.
//
// The plain-text alternative is generated in every case, including when an HTML
// part exists. It costs a few hundred bytes, it is what a reader with a text
// client actually sees, and generating it from the same blocks means the two
// cannot disagree about what the message says.

import (
	"bytes"
	"database/sql"
	"fmt"
	"html"
	"strings"

	message "github.com/emersion/go-message"
)

// renderPlain renders a draft's blocks as the text/plain body of a mail.
//
// Blocks are separated by a blank line, which is the paragraph break of plain
// text. A quote carries its attribution line above it and every line prefixed,
// which is what a mail client will collapse and what the next reply will quote
// in turn.
func renderPlain(d *draft) string {
	var parts []string
	for _, b := range d.Blocks {
		switch b.Kind {
		case blockText:
			if s := strings.TrimRight(b.Content, "\n"); strings.TrimSpace(s) != "" {
				parts = append(parts, s)
			}
		case blockQuote:
			if strings.TrimSpace(b.Content) == "" {
				continue
			}
			var sb strings.Builder
			if b.Meta.Attribution != "" {
				sb.WriteString(b.Meta.Attribution)
				sb.WriteString("\n")
			}
			sb.WriteString(quoteText(b.Content))
			parts = append(parts, sb.String())
		case blockCode:
			if strings.TrimSpace(b.Content) == "" {
				continue
			}
			// Indented by four spaces, which is the oldest convention for
			// "this is a listing" in plain-text mail and survives being
			// forwarded through clients that know nothing about Markdown. It
			// also stops a line beginning with ">" inside a listing from
			// reading as a quotation.
			parts = append(parts, indent(b.Content, "    "))
		case blockImage:
			// An image has no plain-text form. Naming it is better than
			// silence, which would leave the text reader wondering what the
			// other half of the message was about.
			name := b.Meta.Alt
			if name == "" {
				name = "image"
			}
			parts = append(parts, "["+name+" — attached image]")
		case blockFile:
			// Nothing. An attachment is enclosed beside the body, and every
			// mail client in existence lists what a message carries; writing
			// "[foto.jpg — attached]" into the prose would add a line the
			// account owner did not write, next to a list the recipient is
			// already being shown. The image case above is the exception
			// because an inline image is *in* the body, so leaving it out
			// would drop content rather than avoid repeating it.
		}
	}
	return strings.Join(parts, "\n\n") + "\n"
}

// renderHTML renders a draft's blocks as the text/html body of a mail.
//
// Deliberately plain markup: paragraphs, blockquotes and <pre>. It carries no
// stylesheet, no fonts and no layout, because a reply is prose and because
// every one of those is a thing the recipient's client will fight with. What
// HTML buys here is a code listing that survives intact and an image shown in
// place, and nothing else is worth the bytes.
func renderHTML(d *draft) string {
	var sb strings.Builder
	sb.WriteString("<html><body>\n")
	for _, b := range d.Blocks {
		switch b.Kind {
		case blockText:
			if strings.TrimSpace(b.Content) == "" {
				continue
			}
			// Blank lines separate paragraphs; single breaks stay breaks.
			for _, para := range strings.Split(b.Content, "\n\n") {
				if strings.TrimSpace(para) == "" {
					continue
				}
				fmt.Fprintf(&sb, "<p>%s</p>\n",
					strings.ReplaceAll(html.EscapeString(strings.TrimSpace(para)), "\n", "<br>\n"))
			}
		case blockQuote:
			if strings.TrimSpace(b.Content) == "" {
				continue
			}
			// type="cite" is what mail clients key their quote styling off,
			// and is what mailweb's own message view already styles.
			sb.WriteString("<blockquote type=\"cite\">\n")
			if b.Meta.Attribution != "" {
				fmt.Fprintf(&sb, "<p>%s</p>\n", html.EscapeString(b.Meta.Attribution))
			}
			for _, para := range strings.Split(b.Content, "\n\n") {
				if strings.TrimSpace(para) == "" {
					continue
				}
				fmt.Fprintf(&sb, "<p>%s</p>\n",
					strings.ReplaceAll(html.EscapeString(strings.TrimSpace(para)), "\n", "<br>\n"))
			}
			sb.WriteString("</blockquote>\n")
		case blockCode:
			if strings.TrimSpace(b.Content) == "" {
				continue
			}
			// The one place the markup earns its keep: <pre> is why a draft
			// with a listing is sent as HTML at all.
			fmt.Fprintf(&sb, "<pre>%s</pre>\n",
				html.EscapeString(strings.TrimRight(b.Content, "\n")))
		case blockImage:
			// Inline images are carried as related parts and referenced by
			// Content-ID; until that lands an image block renders as its
			// description rather than as a broken reference. An attached file
			// is a different thing and is not this — see blockFile below and
			// writeMixedBody.
			alt := b.Meta.Alt
			if alt == "" {
				alt = "image"
			}
			fmt.Fprintf(&sb, "<p>[%s]</p>\n", html.EscapeString(alt))
		case blockFile:
			// Nothing, for the reason given in renderPlain: an attachment is
			// not body text in either rendering, and the two must agree about
			// what the message says.
		}
	}
	sb.WriteString("</body></html>\n")
	return sb.String()
}

// indent prefixes every line of s.
func indent(s, prefix string) string {
	lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
	for i, line := range lines {
		if line == "" {
			continue
		}
		lines[i] = prefix + line
	}
	return strings.Join(lines, "\n")
}

// ============================================================================
// Assembling the message
// ============================================================================

// buildDraftMessage renders a draft as the raw bytes of a mail to one recipient
// set.
//
// The recipients are passed in rather than read off the draft because choosing
// which set to use is the act being authorised, and it happens at the call site
// where that authorisation was given. This function addresses what it is told
// to address.
//
// It returns the bytes and the Message-ID it generated, so the caller can
// record what the draft became.
//
// Named for a draft rather than for a reply because most drafts are replies and
// not all of them are: one composed from nothing threads no message and quotes
// nobody, and is otherwise identical. The threading headers come off the draft
// and are simply absent there.
func buildDraftMessage(db *sql.DB, d *draft, from string, set recipientSet) ([]byte, string, error) {
	if len(set.To) == 0 {
		// Refused rather than sent with an empty To:, which some servers
		// accept and deliver to nobody, leaving every local trace saying the
		// mail went out.
		return nil, "", fmt.Errorf(
			"no recipients: a message must name at least one address in To. " +
				"A set holding only Cc addresses cannot be sent; move one of them " +
				"to To")
	}

	var buf bytes.Buffer
	h := draftHeader(d, from, set)
	messageID, err := h.MessageID()
	if err != nil {
		// A message with no readable Message-ID is still worth sending; what
		// is lost is the ability to tie the Sent copy back to this draft.
		messageID = ""
	}

	// The attachments' bytes are read only here. Everything else that touches a
	// draft works from the metadata, so a page render costs a filename and this
	// costs the file.
	attachments, err := loadDraftAttachments(db, d)
	if err != nil {
		return nil, "", err
	}

	// The same question — plain or alternative — asked once, whether the body
	// is the whole message or a part of one. A draft that gained an attachment
	// must not change what its body says.
	rich := d.RichFormat()

	if len(attachments) == 0 {
		var err error
		if rich {
			err = writeAlternativeBody(&buf, h, renderPlain(d), renderHTML(d))
		} else {
			err = writePlainBody(&buf, h, renderPlain(d))
		}
		if err != nil {
			return nil, "", err
		}
		return buf.Bytes(), messageID, nil
	}

	writeBody := func(mw *message.Writer) error {
		if rich {
			return writeAlternativeInto(mw, renderPlain(d), renderHTML(d))
		}
		return writePlainInto(mw, renderPlain(d))
	}
	if err := writeMixedBody(&buf, h, writeBody, attachments); err != nil {
		return nil, "", err
	}
	return buf.Bytes(), messageID, nil
}

// loadDraftAttachments reads the bytes of everything a draft encloses.
//
// A file block whose asset has gone is an error rather than an omission. The
// two are created in one transaction and deleted in one, so a block without its
// asset means something went wrong that nobody has seen — and the failure to
// avoid is sending a mail that quietly lacks the invoice it was written to
// carry. The draft is left untouched and says what is missing.
func loadDraftAttachments(db *sql.DB, d *draft) ([]draftAsset, error) {
	var out []draftAsset
	for _, b := range d.Attachments() {
		if b.AssetID == 0 {
			return nil, fmt.Errorf(
				"the attachment %q has no stored file, so the message was not sent; "+
					"remove the attachment and add it again", b.Content)
		}
		asset, err := loadDraftAsset(db, d.ID, b.AssetID)
		if err != nil {
			return nil, fmt.Errorf("attachment %q: %w", b.Content, err)
		}
		out = append(out, *asset)
	}
	return out, nil
}