summaryrefslogtreecommitdiffstats
path: root/src/messagebuilder.cpp
blob: 04982c9df1f97ecb3e9ffadb870994081ffa695b (plain)
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
285
286
/*
 * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
 * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

// gmime.h pulls in glib's gio headers, which declare a struct field named
// "signals". Qt's <QtCore/qnamespace.h> #defines "signals" to "Q_SIGNALS"
// (unless QT_NO_KEYWORDS is set), so gmime.h must be included before any Qt
// header in this translation unit to avoid a macro collision.
#include <gmime/gmime.h>

#include "messagebuilder.h"

#include <QCoreApplication>
#include <QFileInfo>
#include <QMimeDatabase>
#include <QMimeType>
#include <QObject>

#include "config.h"
#include "markdownrenderer.h"

namespace {

/// GMime must be initialised exactly once per process. MimeParser has its own
/// copy of this guard; both are cheap and neither can assume the other ran,
/// since a test may link only one of them.
void ensureGMimeInitialised()
{
    static bool initialised = false;
    if (!initialised) {
        g_mime_init();
        initialised = true;
    }
}

/// A text part carrying \p text as utf-8, quoted-printable.
///
/// Deliberately NOT g_mime_text_part_set_text(). Measured 2026-08-20: that
/// function encodes using the charset set at the moment it is CALLED, so the
/// obvious "set the text, then set the charset" order relabels the part without
/// re-encoding it. The result is a part headed charset=utf-8 whose bytes are
/// latin-1 (`Perch=E9`), which looks correct in every header and arrives as
/// mojibake. Building the content stream from the utf-8 bytes directly was
/// measured to produce `Perch=C3=A9` correctly. This user writes Italian, so an
/// accented character is in every message, not an edge case.
GMimePart *makeTextPart(const char *subtype, const QString &text)
{
    GMimePart *part = g_mime_part_new_with_type("text", subtype);
    g_mime_object_set_content_type_parameter(GMIME_OBJECT(part), "charset", "utf-8");

    const QByteArray utf8 = text.toUtf8();
    GMimeStream *stream = g_mime_stream_mem_new_with_buffer(utf8.constData(),
                                                           static_cast<size_t>(utf8.size()));
    GMimeDataWrapper *wrapper =
        g_mime_data_wrapper_new_with_stream(stream, GMIME_CONTENT_ENCODING_DEFAULT);
    g_mime_part_set_content(part, wrapper);
    g_mime_part_set_content_encoding(part, GMIME_CONTENT_ENCODING_QUOTEDPRINTABLE);

    g_object_unref(wrapper);
    g_object_unref(stream);
    return part;
}

/// Sets \p header on \p message to \p addresses, RFC 2047 encoded as utf-8.
///
/// Each entry is passed through internet_address_list_parse() rather than
/// treated as a bare address, because the composer's fields hold whatever the
/// user typed and "Name <addr@example.org>" is the ordinary form. Parsing per
/// entry rather than joining first keeps a comma inside a quoted display name
/// from splitting one recipient into two.
void setAddressHeader(GMimeMessage *message, const char *header, const QStringList &addresses)
{
    if (addresses.isEmpty())
        return;

    InternetAddressList *list = internet_address_list_new();
    for (const QString &entry : addresses) {
        const QString trimmed = entry.trimmed();
        if (trimmed.isEmpty())
            continue;
        const QByteArray utf8 = trimmed.toUtf8();
        InternetAddressList *parsed = internet_address_list_parse(nullptr, utf8.constData());
        if (!parsed)
            continue;
        internet_address_list_append(list, parsed);
        g_object_unref(parsed);
    }

    if (internet_address_list_length(list) > 0) {
        GMimeFormatOptions *format = g_mime_format_options_get_default();
        char *rendered = internet_address_list_to_string(list, format, TRUE);
        if (rendered) {
            g_mime_object_set_header(GMIME_OBJECT(message), header, rendered, "utf-8");
            g_free(rendered);
        }
    }
    g_object_unref(list);
}

}  // namespace

namespace MessageBuilder {

Result build(const OutgoingMessage &message, const Account &account)
{
    Result result;

    // Config::account() returns a DEFAULT-CONSTRUCTED Account for an unknown
    // key rather than reporting an error, so an account reached by a stale or
    // mistyped key arrives here looking like a valid one with empty fields.
    // Building from it would produce a message with an empty From: silently
    // malformed mail handed to the send command as though it were fine.
    if (account.address.trimmed().isEmpty()) {
        result.error = QObject::tr("The account has no address configured, so no message "
                                   "can be sent from it.");
        return result;
    }

    // Attachments are checked HERE rather than when the file was attached: a
    // file can vanish in between, and a message missing the thing it was
    // written to carry must never reach the send command. Checked before
    // anything is allocated, so the failure path frees nothing.
    for (const QString &path : message.attachments) {
        const QFileInfo info(path);
        if (!info.exists() || !info.isReadable()) {
            result.error = QObject::tr("The attachment %1 is missing or unreadable.")
                               .arg(info.fileName().isEmpty() ? path : info.fileName());
            return result;
        }
    }

    ensureGMimeInitialised();

    GMimeMessage *mime = g_mime_message_new(TRUE);

    const QByteArray fromName = account.name.toUtf8();
    const QByteArray fromAddress = account.address.toUtf8();
    g_mime_message_add_mailbox(mime, GMIME_ADDRESS_TYPE_FROM,
                               account.name.isEmpty() ? nullptr : fromName.constData(),
                               fromAddress.constData());

    setAddressHeader(mime, "To", message.to);
    setAddressHeader(mime, "Cc", message.cc);
    // Bcc is written into the bytes deliberately. The documented send command
    // is `msmtp -t`, which reads its recipients FROM the headers and strips Bcc
    // itself before transmission; omitting it here would mean blind recipients
    // never receive the message at all, silently. If sending ever passes
    // recipients as arguments instead, this line must go with it.
    setAddressHeader(mime, "Bcc", message.bcc);

    // The explicit "utf-8". Measured 2026-08-20: with NULL here GMime encodes
    // the subject as iso-8859-1 (=?iso-8859-1?B?...?=).
    const QByteArray subject = message.subject.toUtf8();
    g_mime_message_set_subject(mime, subject.constData(), "utf-8");

    if (!message.inReplyTo.trimmed().isEmpty()) {
        const QByteArray value = message.inReplyTo.trimmed().toUtf8();
        g_mime_object_set_header(GMIME_OBJECT(mime), "In-Reply-To", value.constData(), "utf-8");
    }
    if (!message.references.isEmpty()) {
        const QByteArray value = message.references.join(QLatin1Char(' ')).toUtf8();
        g_mime_object_set_header(GMIME_OBJECT(mime), "References", value.constData(), "utf-8");
    }

    // Measured 2026-08-20: GMime generates neither Date nor Message-ID unless
    // asked. A message without a Message-ID cannot be threaded by anything that
    // receives it, this application's own index of the sent copy included.
    GDateTime *now = g_date_time_new_now_local();
    g_mime_message_set_date(mime, now);
    g_date_time_unref(now);

    const QString domain = account.address.section(QLatin1Char('@'), 1);
    const QByteArray domainUtf8 = (domain.isEmpty() ? QStringLiteral("localhost") : domain).toUtf8();
    char *generatedId = g_mime_utils_generate_message_id(domainUtf8.constData());
    if (generatedId) {
        g_mime_message_set_message_id(mime, generatedId);
        result.messageId = QString::fromUtf8(generatedId);
        g_free(generatedId);
    }

    // The markdown SOURCE is the plain part, never a stripped-of-syntax
    // rewrite: `**bold**` reads as emphasis, and rewriting it would mean a
    // second renderer whose output could disagree with the HTML one.
    GMimeObject *body = GMIME_OBJECT(makeTextPart("plain", message.markdownBody));

    if (message.sendHtml) {
        GMimePart *html = makeTextPart("html", MarkdownRenderer::toHtml(message.markdownBody));
        GMimeMultipart *alternative = g_mime_multipart_new_with_subtype("alternative");
        // Least-rich FIRST. A client renders the LAST alternative it
        // understands, so a reversed order shows the markdown source everywhere
        // and the rendered part is never seen.
        g_mime_multipart_add(alternative, body);
        g_mime_multipart_add(alternative, GMIME_OBJECT(html));
        g_object_unref(body);
        g_object_unref(html);
        body = GMIME_OBJECT(alternative);
    }

    if (!message.attachments.isEmpty()) {
        GMimeMultipart *mixed = g_mime_multipart_new_with_subtype("mixed");
        // The body goes in FIRST, so the wrapper NESTS it rather than standing
        // beside it. Beside it, a client shows the alternatives as attachments
        // and the message reads as empty.
        g_mime_multipart_add(mixed, body);
        g_object_unref(body);

        QMimeDatabase mimeDb;
        for (const QString &path : message.attachments) {
            const QFileInfo info(path);
            const QMimeType type = mimeDb.mimeTypeForFile(info);
            const QByteArray typeName = type.name().toUtf8();

            GMimeContentType *contentType =
                g_mime_content_type_parse(nullptr, typeName.isEmpty()
                                                       ? "application/octet-stream"
                                                       : typeName.constData());
            GMimePart *part = g_mime_part_new();
            if (contentType) {
                g_mime_object_set_content_type(GMIME_OBJECT(part), contentType);
                g_object_unref(contentType);
            }

            GMimeStream *stream = g_mime_stream_file_open(path.toLocal8Bit().constData(),
                                                          "r", nullptr);
            if (!stream) {
                // Existence was checked above, so reaching here means the file
                // went away between the check and the read. Fail rather than
                // send a message with a hole in it.
                g_object_unref(part);
                g_object_unref(mixed);
                g_object_unref(mime);
                result.bytes.clear();
                result.messageId.clear();
                result.error = QObject::tr("The attachment %1 could not be read.")
                                   .arg(info.fileName());
                return result;
            }
            GMimeDataWrapper *wrapper =
                g_mime_data_wrapper_new_with_stream(stream, GMIME_CONTENT_ENCODING_DEFAULT);
            g_mime_part_set_content(part, wrapper);
            g_mime_part_set_content_encoding(part, GMIME_CONTENT_ENCODING_BASE64);
            g_object_unref(wrapper);
            g_object_unref(stream);

            const QByteArray filename = info.fileName().toUtf8();
            g_mime_part_set_filename(part, filename.constData());
            g_mime_object_set_disposition(GMIME_OBJECT(part), "attachment");

            g_mime_multipart_add(mixed, GMIME_OBJECT(part));
            g_object_unref(part);
        }
        body = GMIME_OBJECT(mixed);
    }

    g_mime_message_set_mime_part(mime, body);
    g_object_unref(body);

    GMimeFormatOptions *format = g_mime_format_options_get_default();
    char *rendered = g_mime_object_to_string(GMIME_OBJECT(mime), format);
    if (rendered) {
        result.bytes = QByteArray(rendered);
        g_free(rendered);
    } else {
        result.error = QObject::tr("The message could not be assembled.");
        result.messageId.clear();
    }

    g_object_unref(mime);
    return result;
}

}  // namespace MessageBuilder