1// Package dsn parses and composes Delivery Status Notification messages, see
2// RFC 3464 and RFC 6533.
18 "github.com/mjl-/mox/message"
19 "github.com/mjl-/mox/mlog"
20 "github.com/mjl-/mox/smtp"
23// Message represents a DSN message, with basic message headers, human-readable text,
24// machine-parsable data, and optional original message/headers.
26// A DSN represents a delayed, failed or successful delivery. Failing incoming
27// deliveries over SMTP, and failing outgoing deliveries from the message queue,
28// can result in a DSN being sent.
30 SMTPUTF8 bool // Whether the original was received with smtputf8.
32 // DSN message From header. E.g. postmaster@ourdomain.example. NOTE:
33 // DSNs should be sent with a null reverse path to prevent mail loops.
37 // "To" header, and also SMTP RCP TO to deliver DSN to. Should be taken
38 // from original SMTP transaction MAIL FROM.
42 // Message subject header, e.g. describing mail delivery failure.
47 // References header, with Message-ID of original message this DSN is about. So
48 // mail user-agents will thread the DSN with the original message.
51 // Human-readable text explaining the failure. Line endings should be
52 // bare newlines, not \r\n. They are converted to \r\n when composing.
55 // Per-message fields.
56 OriginalEnvelopeID string
57 ReportingMTA string // Required.
59 ReceivedFromMTA smtp.Ehlo // Host from which message was received.
62 // All per-message fields, including extensions. Only used for parsing,
64 MessageHeader textproto.MIMEHeader
66 // One or more per-recipient fields.
68 Recipients []Recipient
70 // Original message or headers to include in DSN as third MIME part.
71 // Optional. Only used for generating DSNs, not set for parsed DNSs.
75// Action is a field in a DSN.
81 Failed Action = "failed"
82 Delayed Action = "delayed"
83 Delivered Action = "delivered"
84 Relayed Action = "relayed"
85 Expanded Action = "expanded"
90// Recipient holds the per-recipient delivery-status lines in a DSN.
91type Recipient struct {
93 FinalRecipient smtp.Path // Final recipient of message.
96 // Enhanced status code. First digit indicates permanent or temporary
97 // error. If the string contains more than just a status, that
98 // additional text is added as comment when composing a DSN.
102 // Original intended recipient of message. Used with the DSN extensions ORCPT
105 OriginalRecipient smtp.Path
107 // Remote host that returned an error code. Can also be empty for
111 // If RemoteMTA is present, DiagnosticCode is from remote. When
112 // creating a DSN, additional text in the string will be added to the
114 DiagnosticCode string
115 LastAttemptDate time.Time
118 // For delayed deliveries, deliveries may be retried until this time.
119 WillRetryUntil *time.Time
121 // All fields, including extensions. Only used for parsing, not
123 Header textproto.MIMEHeader
126// Compose returns a DSN message.
128// smtputf8 indicates whether the remote MTA that is receiving the DSN
129// supports smtputf8. This influences the message media (sub)types used for the
132// Called may want to add DKIM-Signature headers.
133func (m *Message) Compose(log mlog.Log, smtputf8 bool) ([]byte, error) {
136 // We'll make a multipart/report with 2 or 3 parts:
137 // - 1. human-readable explanation;
138 // - 2. message/delivery-status;
139 // - 3. (optional) original message (either in full, or only headers).
141 // todo future: add option to send full message. but only do so if the message is <100kb.
142 // todo future: possibly write to a file directly, instead of building up message in memory.
144 // If message does not require smtputf8, we are never generating a utf-8 DSN.
149 // We check for errors once after all the writes.
150 msgw := &errWriter{w: &bytes.Buffer{}}
152 header := func(k, v string) {
153 fmt.Fprintf(msgw, "%s: %s\r\n", k, v)
156 line := func(w io.Writer) {
157 _, _ = w.Write([]byte("\r\n"))
160 // Outer message headers.
161 header("From", fmt.Sprintf("<%s>", m.From.XString(smtputf8))) // todo: would be good to have a local ascii-only name for this address.
162 header("To", fmt.Sprintf("<%s>", m.To.XString(smtputf8))) // todo: we could just leave this out if it has utf-8 and remote does not support utf-8.
163 header("Subject", m.Subject)
164 if m.MessageID == "" {
165 return nil, fmt.Errorf("missing message-id")
167 header("Message-Id", fmt.Sprintf("<%s>", m.MessageID))
168 if m.References != "" {
169 header("References", m.References)
171 header("Date", time.Now().Format(message.RFC5322Z))
172 header("MIME-Version", "1.0")
173 mp := multipart.NewWriter(msgw)
174 header("Content-Type", fmt.Sprintf(`multipart/report; report-type="delivery-status"; boundary="%s"`, mp.Boundary()))
178 // First part, human-readable message.
179 msgHdr := textproto.MIMEHeader{}
181 msgHdr.Set("Content-Type", "text/plain; charset=utf-8")
182 msgHdr.Set("Content-Transfer-Encoding", "8BIT")
184 msgHdr.Set("Content-Type", "text/plain")
185 msgHdr.Set("Content-Transfer-Encoding", "7BIT")
187 msgp, err := mp.CreatePart(msgHdr)
191 if _, err := msgp.Write([]byte(strings.ReplaceAll(m.TextBody, "\n", "\r\n"))); err != nil {
196 statusHdr := textproto.MIMEHeader{}
199 statusHdr.Set("Content-Type", "message/global-delivery-status")
200 statusHdr.Set("Content-Transfer-Encoding", "8BIT")
202 statusHdr.Set("Content-Type", "message/delivery-status")
203 statusHdr.Set("Content-Transfer-Encoding", "7BIT")
205 statusp, err := mp.CreatePart(statusHdr)
212 // type fields:
../rfc/3464:536 https://www.iana.org/assignments/dsn-types/dsn-types.xhtml
214 status := func(k, v string) {
215 fmt.Fprintf(statusp, "%s: %s\r\n", k, v)
220 if m.OriginalEnvelopeID != "" {
221 status("Original-Envelope-ID", m.OriginalEnvelopeID)
224 if m.DSNGateway != "" {
226 status("DSN-Gateway", "dns; "+m.DSNGateway)
228 if !m.ReceivedFromMTA.IsZero() {
230 status("Received-From-MTA", fmt.Sprintf("dns;%s (%s)", m.ReceivedFromMTA.Name, smtp.AddressLiteral(m.ReceivedFromMTA.ConnIP)))
235 // todo: should also handle other address types. at least recognize "unknown". Probably just store this field.
../rfc/3464:819
240 if len(m.Recipients) == 0 {
241 return nil, fmt.Errorf("missing per-recipient fields")
243 for _, r := range m.Recipients {
245 if !r.OriginalRecipient.IsZero() {
247 status("Original-Recipient", addrType+r.OriginalRecipient.DSNString(smtputf8))
249 status("Final-Recipient", addrType+r.FinalRecipient.DSNString(smtputf8)) //
../rfc/3464:829
254 // Making up a status code is not great, but the field is required. We could simply
255 // require the caller to make one up...
266 st, rest = codeLine(st)
269 statusLine += " (" + rest + ")"
272 if !r.RemoteMTA.IsZero() {
274 s := "dns;" + r.RemoteMTA.Name
275 if len(r.RemoteMTA.IP) > 0 {
276 s += " (" + smtp.AddressLiteral(r.RemoteMTA.IP) + ")"
278 status("Remote-MTA", s)
281 if r.DiagnosticCode != "" {
282 diagCode, rest := codeLine(r.DiagnosticCode)
285 diagLine += " (" + rest + ")"
288 status("Diagnostic-Code", "smtp; "+diagLine)
290 if !r.LastAttemptDate.IsZero() {
291 status("Last-Attempt-Date", r.LastAttemptDate.Format(message.RFC5322Z)) //
../rfc/3464:1076
293 if r.FinalLogID != "" {
294 // todo future: think about adding cid as "Final-Log-Id"?
297 if r.WillRetryUntil != nil {
302 // We include only the header of the original message.
303 // todo: add the textual version of the original message, if it exists and isn't too large.
304 if m.Original != nil {
305 headers, err := message.ReadHeaders(bufio.NewReader(bytes.NewReader(m.Original)))
306 if err != nil && errors.Is(err, message.ErrHeaderSeparator) {
307 // Whole data is a header.
309 } else if err != nil {
312 // Else, this is a whole message. We still only include the headers. todo: include the whole body.
314 origHdr := textproto.MIMEHeader{}
319 origHdr.Set("Content-Transfer-Encoding", "8BIT")
324 origHdr.Set("Content-Type", "text/rfc822-headers; charset=utf-8")
325 origHdr.Set("Content-Transfer-Encoding", "BASE64")
327 origHdr.Set("Content-Type", "text/rfc822-headers")
328 origHdr.Set("Content-Transfer-Encoding", "7BIT")
331 origp, err := mp.CreatePart(origHdr)
336 if !smtputf8 && m.SMTPUTF8 {
337 data := base64.StdEncoding.EncodeToString(headers)
344 line, data = data[:n], data[n:]
345 if _, err := origp.Write([]byte(line + "\r\n")); err != nil {
350 if _, err := origp.Write(headers); err != nil {
356 if err := mp.Close(); err != nil {
364 data := msgw.w.Bytes()
368type errWriter struct {
373func (w *errWriter) Write(buf []byte) (int, error) {
377 n, err := w.w.Write(buf)
382// split a line into enhanced status code and rest.
383func codeLine(s string) (string, string) {
384 t := strings.SplitN(s, " ", 2)
385 l := strings.Split(t[0], ".")
389 for i, e := range l {
390 _, err := strconv.ParseInt(e, 10, 32)
394 if i == 0 && len(e) != 1 {
406// HasCode returns whether line starts with an enhanced SMTP status code.
407func HasCode(line string) bool {
409 ecode, _ := codeLine(line)