| 1 |
package smtp |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/rand" |
| 5 |
"encoding/hex" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"maps" |
| 9 |
"mime" |
| 10 |
"net/mail" |
| 11 |
"slices" |
| 12 |
"strings" |
| 13 |
"time" |
| 14 |
|
| 15 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 16 |
) |
| 17 |
|
| 18 |
const ( |
| 19 |
// contentHTML is the Content-Type for HTML message parts. |
| 20 |
contentHTML = "text/html; charset=\"UTF-8\"" |
| 21 |
// contentPlain is the Content-Type for plain-text message parts. |
| 22 |
contentPlain = "text/plain; charset=\"UTF-8\"" |
| 23 |
// contentMultipart is the Content-Type format string for multipart/alternative messages. |
| 24 |
contentMultipart = "multipart/alternative; boundary=%s" |
| 25 |
// boundaryByteLen is the number of random bytes used to generate a multipart boundary |
| 26 |
// and Message-ID token. |
| 27 |
boundaryByteLen = 8 |
| 28 |
// templatePlain is the Templater ID for the text/plain part. |
| 29 |
templatePlain = "plain" |
| 30 |
// templateHTML is the Templater ID for the text/html part. |
| 31 |
templateHTML = "HTML" |
| 32 |
// maxHeaderLineOctets is the RFC 5322 maximum length of a header line, |
| 33 |
// excluding the CRLF. See https://datatracker.ietf.org/doc/html/rfc5322#section-2.1.1. |
| 34 |
maxHeaderLineOctets = 998 |
| 35 |
) |
| 36 |
|
| 37 |
// headers constructs email headers for the SMTP message. |
| 38 |
// |
| 39 |
// Non-ASCII header values are encoded per RFC 2047 |
| 40 |
// (https://datatracker.ietf.org/doc/html/rfc2047). The Subject value is folded |
| 41 |
// to [maxHeaderLineOctets]. When [Config.UseHTML] is true, the Content-Type is |
| 42 |
// multipart/alternative with the given boundary. |
| 43 |
// |
| 44 |
// Parameters: |
| 45 |
// - config: SMTP configuration providing sender, subject, and HTML options. |
| 46 |
// - toAddress: The recipient address for the To header. |
| 47 |
// - boundary: Multipart boundary used when HTML mail is enabled. |
| 48 |
// |
| 49 |
// Returns: |
| 50 |
// - A map of header names to encoded values. |
| 51 |
func headers(config *Config, toAddress, boundary string) map[string]string { |
| 52 |
var contentType string |
| 53 |
if config.UseHTML { |
| 54 |
contentType = fmt.Sprintf(contentMultipart, boundary) |
| 55 |
} else { |
| 56 |
contentType = contentPlain |
| 57 |
} |
| 58 |
|
| 59 |
// Header values must be US-ASCII per RFC 5322 section 2.2 |
| 60 |
// (https://datatracker.ietf.org/doc/html/rfc5322#section-2.2), so any |
| 61 |
// non-ASCII content is wrapped in RFC 2047 encoded-words |
| 62 |
// (https://datatracker.ietf.org/doc/html/rfc2047). Pure ASCII values are |
| 63 |
// passed through as-is. |
| 64 |
from := &mail.Address{Name: config.FromName, Address: config.FromAddress} |
| 65 |
recipient := &mail.Address{Name: "", Address: toAddress} |
| 66 |
|
| 67 |
headerMap := map[string]string{ |
| 68 |
"Subject": foldHeaderValue( |
| 69 |
"Subject", |
| 70 |
mime.QEncoding.Encode("UTF-8", config.Subject), |
| 71 |
), |
| 72 |
"Date": time.Now().Format(time.RFC1123Z), |
| 73 |
"To": recipient.String(), |
| 74 |
"From": from.String(), |
| 75 |
"Message-ID": generateMessageID(config.FromAddress), |
| 76 |
"MIME-version": "1.0", |
| 77 |
"Content-Type": contentType, |
| 78 |
} |
| 79 |
if !config.UseHTML { |
| 80 |
headerMap["Content-Transfer-Encoding"] = "8bit" |
| 81 |
} |
| 82 |
|
| 83 |
return headerMap |
| 84 |
} |
| 85 |
|
| 86 |
// generateMessageID returns an RFC 5322 Message-ID using the sender domain. |
| 87 |
// |
| 88 |
// See https://datatracker.ietf.org/doc/html/rfc5322#section-3.6.4. |
| 89 |
// |
| 90 |
// Parameters: |
| 91 |
// - fromAddress: The sender address whose domain is used in the Message-ID. |
| 92 |
// |
| 93 |
// Returns: |
| 94 |
// - A Message-ID of the form <id@domain>. The domain falls back to localhost |
| 95 |
// when fromAddress has no host part. |
| 96 |
func generateMessageID(fromAddress string) string { |
| 97 |
domain := "localhost" |
| 98 |
if _, host, found := strings.Cut(fromAddress, "@"); found && host != "" { |
| 99 |
domain = host |
| 100 |
} |
| 101 |
|
| 102 |
b := make([]byte, boundaryByteLen) |
| 103 |
if _, err := rand.Read(b); err != nil { |
| 104 |
return fmt.Sprintf("<%d@%s>", time.Now().UnixNano(), domain) |
| 105 |
} |
| 106 |
|
| 107 |
return fmt.Sprintf("<%s@%s>", hex.EncodeToString(b), domain) |
| 108 |
} |
| 109 |
|
| 110 |
// foldHeaderValue folds an unstructured header value to RFC 5322 line limits. |
| 111 |
// |
| 112 |
// Existing RFC 5322 folding whitespace is unfolded first so the function is |
| 113 |
// idempotent. The first physical line is limited so that `name: value` stays |
| 114 |
// within [maxHeaderLineOctets]; continuation lines start with a single space. |
| 115 |
// |
| 116 |
// Parameters: |
| 117 |
// - name: The header field name, used to size the first line. |
| 118 |
// - value: The header field body, which may already be folded. |
| 119 |
// |
| 120 |
// Returns: |
| 121 |
// - The header body with `\n ` inserted so no physical line exceeds [maxHeaderLineOctets]. |
| 122 |
func foldHeaderValue(name, value string) string { |
| 123 |
unfolded := strings.ReplaceAll(value, "\r\n ", "") |
| 124 |
unfolded = strings.ReplaceAll(unfolded, "\n ", "") |
| 125 |
unfolded = strings.ReplaceAll(unfolded, "\r ", "") |
| 126 |
|
| 127 |
firstLimit := max(maxHeaderLineOctets-len(name)-len(": "), 1) |
| 128 |
|
| 129 |
if len(unfolded) <= firstLimit { |
| 130 |
return unfolded |
| 131 |
} |
| 132 |
|
| 133 |
var builder strings.Builder |
| 134 |
|
| 135 |
builder.Grow(len(unfolded) + len(unfolded)/firstLimit*2) |
| 136 |
|
| 137 |
remaining := unfolded |
| 138 |
limit := firstLimit |
| 139 |
|
| 140 |
for remaining != "" { |
| 141 |
n := min(limit, len(remaining)) |
| 142 |
builder.WriteString(remaining[:n]) |
| 143 |
remaining = remaining[n:] |
| 144 |
|
| 145 |
if remaining != "" { |
| 146 |
builder.WriteString("\n ") |
| 147 |
|
| 148 |
limit = maxHeaderLineOctets - 1 |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
return builder.String() |
| 153 |
} |
| 154 |
|
| 155 |
// generateBoundary returns a random multipart boundary token. |
| 156 |
func generateBoundary() (string, error) { |
| 157 |
b := make([]byte, boundaryByteLen) |
| 158 |
if _, err := rand.Read(b); err != nil { |
| 159 |
return "", fmt.Errorf("generating multipart boundary: %w", err) |
| 160 |
} |
| 161 |
|
| 162 |
return hex.EncodeToString(b), nil |
| 163 |
} |
| 164 |
|
| 165 |
// writeHeaders writes email headers to the provided writer. |
| 166 |
// |
| 167 |
// Keys are written in sorted order. Values are folded to [maxHeaderLineOctets]. |
| 168 |
// A blank line is written after the headers to separate them from the body. |
| 169 |
// |
| 170 |
// Parameters: |
| 171 |
// - writer: The DATA stream writer. |
| 172 |
// - headerMap: Header names and values to write. |
| 173 |
// |
| 174 |
// Returns: |
| 175 |
// - An error if a header line or the trailing blank line cannot be written. |
| 176 |
func writeHeaders(writer io.Writer, headerMap map[string]string) error { |
| 177 |
for _, key := range slices.Sorted(maps.Keys(headerMap)) { |
| 178 |
val := foldHeaderValue(key, headerMap[key]) |
| 179 |
if _, err := fmt.Fprintf(writer, "%s: %s\n", key, val); err != nil { |
| 180 |
return fail(FailWriteHeaders, err) |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
_, err := fmt.Fprintln(writer) |
| 185 |
if err != nil { |
| 186 |
return fail(FailWriteHeaders, err) |
| 187 |
} |
| 188 |
|
| 189 |
return nil |
| 190 |
} |
| 191 |
|
| 192 |
// writeAlternative writes a multipart/alternative email body. |
| 193 |
// |
| 194 |
// It writes a text/plain part followed by a text/html part, then the closing |
| 195 |
// boundary. |
| 196 |
// |
| 197 |
// Parameters: |
| 198 |
// - writer: The DATA stream writer. |
| 199 |
// - message: The notification body used for both parts. |
| 200 |
// - boundary: The multipart boundary string. |
| 201 |
// - templates: Template source for the plain and HTML parts. |
| 202 |
// |
| 203 |
// Returns: |
| 204 |
// - An error if a part header or body cannot be written. |
| 205 |
func writeAlternative( |
| 206 |
writer io.Writer, |
| 207 |
message string, |
| 208 |
boundary string, |
| 209 |
templates types.Templater, |
| 210 |
) error { |
| 211 |
if err := writePartHeader(writer, boundary, contentPlain); err != nil { |
| 212 |
return fail(FailPlainHeader, err) |
| 213 |
} |
| 214 |
|
| 215 |
if err := writePart(writer, message, templatePlain, templates); err != nil { |
| 216 |
return err |
| 217 |
} |
| 218 |
|
| 219 |
if err := writePartHeader(writer, boundary, contentHTML); err != nil { |
| 220 |
return fail(FailHTMLHeader, err) |
| 221 |
} |
| 222 |
|
| 223 |
if err := writePart(writer, message, templateHTML, templates); err != nil { |
| 224 |
return err |
| 225 |
} |
| 226 |
|
| 227 |
if err := writePartHeader(writer, boundary, ""); err != nil { |
| 228 |
return fail(FailMultiEndHeader, err) |
| 229 |
} |
| 230 |
|
| 231 |
return nil |
| 232 |
} |
| 233 |
|
| 234 |
// writePart writes a single message part using the named template when registered. |
| 235 |
// |
| 236 |
// When no template is registered for the part, the raw message is written. |
| 237 |
// |
| 238 |
// Parameters: |
| 239 |
// - writer: The DATA stream writer. |
| 240 |
// - message: The notification body. |
| 241 |
// - templateName: The template name to apply, typically [templatePlain] or [templateHTML]. |
| 242 |
// - templates: Template source for the part. |
| 243 |
// |
| 244 |
// Returns: |
| 245 |
// - An error if the template cannot be executed or the raw message cannot be written. |
| 246 |
func writePart(writer io.Writer, message, templateName string, templates types.Templater) error { |
| 247 |
if tpl, found := templates.GetTemplate(templateName); found { |
| 248 |
data := map[string]string{ |
| 249 |
"message": message, |
| 250 |
} |
| 251 |
if err := tpl.Execute(writer, data); err != nil { |
| 252 |
return fail(FailMessageTemplate, err) |
| 253 |
} |
| 254 |
|
| 255 |
return nil |
| 256 |
} |
| 257 |
|
| 258 |
if _, err := fmt.Fprint(writer, message); err != nil { |
| 259 |
return fail(FailMessageRaw, err) |
| 260 |
} |
| 261 |
|
| 262 |
return nil |
| 263 |
} |
| 264 |
|
| 265 |
// writePartHeader writes a multipart boundary header to the provided writer. |
| 266 |
// |
| 267 |
// An empty contentType writes the closing boundary. |
| 268 |
// |
| 269 |
// Parameters: |
| 270 |
// - writer: The DATA stream writer. |
| 271 |
// - boundary: The multipart boundary string. |
| 272 |
// - contentType: The Content-Type for the next part, or empty to close the multipart body. |
| 273 |
// |
| 274 |
// Returns: |
| 275 |
// - An error if the boundary or content-type header cannot be written. |
| 276 |
func writePartHeader(writer io.Writer, boundary, contentType string) error { |
| 277 |
suffix := "\n" |
| 278 |
if contentType == "" { |
| 279 |
suffix = "--" |
| 280 |
} |
| 281 |
|
| 282 |
if _, err := fmt.Fprintf(writer, "\n\n--%s%s", boundary, suffix); err != nil { |
| 283 |
return fmt.Errorf("writing multipart boundary: %w", err) |
| 284 |
} |
| 285 |
|
| 286 |
if contentType != "" { |
| 287 |
if _, err := fmt.Fprintf( |
| 288 |
writer, |
| 289 |
"Content-Type: %s\nContent-Transfer-Encoding: 8bit\n\n", |
| 290 |
contentType, |
| 291 |
); err != nil { |
| 292 |
return fmt.Errorf("writing content type header: %w", err) |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
return nil |
| 297 |
} |