Outbound Email Attachments Developer Guide - edmozley/freeitsm GitHub Wiki
Fixes #158 Β· Changelog #2045β#2049, #2055, #2081 Β· Shipped in 2.10.0 Β· Corrected in 2.10.1
β οΈ 2.10.0 declaredINLINE_THREAD_BUDGETbelow the code that sends, so any reply quoting a picture from the ticket died withUndefined constant. Section 3 now shows where it lives and why. The write-up: Replies with a picture in the thread failed to send.
How a reply or forward becomes an email, on each of the three providers, and what changed to make attachments and pictures actually arrive. For the bug report itself and what it meant for users, see Reply attachments never reached the customer.
Thanks to An Duong (@duongtuanan), who reported it with the raw message Exchange received β the single line Content-Type: text/html that made the cause obvious β and to @mbsouth, who confirmed it on Forward.
api/tickets/send_email.php
β
ββ buildFullEmailBody() analyst's HTML + "reply above this line" + quoted thread
β
ββ provider = Microsoft ββΊ buildEmailMessage() ββΊ JSON { body, attachments[] } ββΊ Graph sendMail
β ββ processInlineImages() + uploadedFileParts()
β
ββ provider = SMTP / Gmail ββΊ processInlineImages() + uploadedFileParts()
ββ mimeBuildMessage() (includes/mime_message.php)
ββ SMTP: imapSmtpSend() writes it down the socket
ββ Gmail: gmailSendEmail() posts it, base64url, to the API
The key idea: all three providers are now fed the same list of files. Microsoft takes that list as JSON and builds the email itself; SMTP and Gmail need a finished email, and mimeBuildMessage() builds it from the same list.
π§± builder Β· π€ send Β· πΌοΈ pictures Β· π§ͺ test
| π¨ | File | What it does |
|---|---|---|
| π§± | includes/mime_message.php |
New. mimeBuildMessage() β the raw RFC 5322 / MIME message for SMTP and Gmail |
| π€ | api/tickets/send_email.php |
Chooses the provider; gathers the files; processInlineImages(), uploadedFileParts()
|
| π€ | includes/mailbox_imap.php |
imapSmtpSend() β the dependency-free SMTP client; now takes $parts
|
| π€ | includes/gmail.php |
gmailSendEmail() β now takes $cc and $parts
|
| π§ͺ | tests/outbound-email-mime.php |
29 checks, including a real SMTP round trip to a fake server |
Also benefit, untouched: includes/template_email.php, includes/self_service_email.php, api/auth/request_password_reset.php and workflow/includes/engine.php call the same two send functions without $parts, so they get the plain HTML email they always did β plus, on SMTP, the new Date and Message-ID headers.
Everything is expressed in Microsoft Graph's fileAttachment shape, because the Graph path already used it:
['name' => 'report.pdf', 'contentType' => 'application/pdf',
'contentBytes' => '<base64>', // an ordinary attachment
'contentId' => 'inline_image_1_1790805999', 'isInline' => true] // add these two for a picture in the bodyThe analyst's uploaded files are converted by one small function, now shared by all three paths:
function uploadedFileParts($attachments) {
$parts = [];
foreach ((array)$attachments as $attachment) {
if (!is_array($attachment) || !isset($attachment['name'], $attachment['content'])) {
continue;
}
$parts[] = [
'@odata.type' => '#microsoft.graph.fileAttachment',
'name' => $attachment['name'],
'contentType' => $attachment['type'] ?? 'application/octet-stream',
'contentBytes' => $attachment['content'] // Already base64 encoded
];
}
return $parts;
}And the send itself ($provider is a MailboxProvider - see Mailbox providers):
if ($provider === MailboxProvider::Imap || $provider === MailboxProvider::Google) {
$inline = processInlineImages($bodyForSending, (int)$ticketId);
$parts = array_merge($inline['attachments'], uploadedFileParts($attachments));
if ($provider === MailboxProvider::Imap) {
imapSmtpSend($mailbox, $to, $cc, $subject, $inline['body'], $parts);
} else {
gmailSendEmail($accessToken, $to, $subject, $inline['body'], $mailbox['target_mailbox'] ?? '', $cc, $parts);
}
} else {
$message = buildEmailMessage($to, $cc, $subject, $bodyForSending, $attachments, (int)$ticketId);
$result = sendEmailViaGraph($accessToken, $message);
}Before the fix the first branch was two separate calls that passed $bodyForSending and nothing else. The ticket then saved $attachments as "sent", so everything on FreeITSM's side said the customer had the file.
mimeBuildMessage() builds the email only as deep as it needs to be:
| The reply has | Structure |
|---|---|
| Just text |
text/html β byte-for-byte the shape sent before #158 |
| Pictures in the body | multipart/related { html, image, image⦠} |
| Attached files | multipart/mixed { html-or-related, file, file⦠} |
$body = mimeHtmlPart((string)($m['html'] ?? ''));
if ($inline) {
$body = mimeMultipart('related', array_merge([$body], array_map('mimeFilePart', $inline)), 'type="text/html"');
}
if ($files) {
$body = mimeMultipart('mixed', array_merge([$body], array_map('mimeFilePart', $files)));
}
// $body is [headers, content]; its headers become the message's own.
return implode("\r\n", array_merge($headers, $body[0])) . "\r\n\r\n" . $body[1];Each entity is a [headers, content] pair, so nesting is just wrapping: a related becomes one entity inside a mixed. Everything is base64 in 76-character lines, so no body line can ever begin with the . that would end an SMTP DATA block (the SMTP client dot-stuffs anyway).
A file's name and type come from the analyst's browser, so they are treated as hostile:
// Only a plain type/subtype reaches the header
$type = strtolower((string)($p['contentType'] ?? ''));
if (!preg_match('#^[a-z0-9][a-z0-9!\#$&^_.+-]*/[a-z0-9][a-z0-9!\#$&^_.+-]*$#', $type)) {
$type = 'application/octet-stream';
}
// An ASCII fallback name, plus RFC 2231 for the real UTF-8 name
$name = str_replace(["\r", "\n", '"', '\\'], '', $name);
$ascii = preg_replace('/[^\x20-\x7E]/', '_', $name);
$fileParam = 'filename="' . $ascii . '"';
if ($ascii !== $name) {
$fileParam .= "; filename*=UTF-8''" . rawurlencode($name);
}The test sends a type of application/pdf\r\nBcc: [email protected] and checks no Bcc: header appears. Recipients go through FILTER_VALIDATE_EMAIL on both paths, and the subject and sender name are RFC 2047-encoded with line breaks removed.
RFC 5322 requires both, and spam filters score a message without them. The Gmail API stamps its own (the raw sent copies show Date: and Message-Id: <β¦@mail.gmail.com> that FreeITSM never wrote), but nothing on the SMTP path did. So they're added on request, and only imapSmtpSend() asks:
if (!empty($m['envelope'])) {
$headers[] = 'Date: ' . gmdate('D, d M Y H:i:s') . ' +0000';
$headers[] = 'Message-ID: ' . mimeMessageId($from); // <random.time@sender-domain>
}A picture in an email body only displays if it travels inside the email, referenced as src="cid:β¦". Two kinds of picture needed converting.
When an email with pictures arrives, FreeITSM saves each picture and rewrites its tag to point back at itself:
<img src="/api/tickets/get_attachment.php?cid=image001.png@01DC...&email_id=326">Every reply quotes the thread, so that link travels to the customer, whose mail client can't reach it. The converter existed, but looked for api/get_attachment.php β a form no stored email contains. It had converted nothing, on any provider. The pattern now takes any relative link, in any of the forms that have been stored:
$pattern = '/src=(["\'])(?![a-z][a-z0-9+.\-]*:)[^"\']*?api\/(?:tickets\/)?get_attachment\.php\?([^"\']+)\1/i';The (?!β¦:) refuses anything with a scheme, so https://someone-else/api/get_attachment.php is left alone.
Only this ticket's files. The old lookup took any attachment id. An analyst can edit a reply's HTML source, so a typed-in link could have mailed out another ticket's β on a multi-company install, another company's β file. Both lookups now join to the email's ticket:
$sql = "SELECT a.id, a.filename, a.content_type, a.file_path
FROM email_attachments a
JOIN emails e ON e.id = a.email_id
WHERE a.id = ? AND e.ticket_id = ?";At most 2 MB per email. Every reply re-sends the whole thread's pictures, and Graph refuses a request over 4 MB. Uncapped, a picture-heavy thread would have gone from "sends with broken pictures" to "doesn't send" β on Microsoft, which was never reported broken. Past the cap a picture keeps its link, as before:
// At the TOP of send_email.php, under the require_once lines:
const INLINE_THREAD_BUDGET = 2 * 1024 * 1024;
// ...and inside processInlineImages():
$size = (int)filesize($filePath);
if ($threadBytes + $size > INLINE_THREAD_BUDGET) {
return $matches[0]; // leave this one as a link
}
$threadBytes += $size;π΄ The constant must stay at the top. A function anywhere in a PHP file exists as soon as the file starts; a top-level const exists only once execution reaches its line. send_email.php does its work at the top and keeps its functions below, so a constant declared down beside processInlineImages() β where 2.10.0 put it β is never defined when a reply is sent. It was read only when a thread picture from the ticket was found, so 2.10.0 failed exactly those replies and sent the rest (#2081).
The picture callback catches Throwable, not just Exception, so a fault embedding one picture leaves that link as it was rather than failing the whole email:
} catch (Throwable $e) {
error_log('Inline image processing error: ' . $e->getMessage());
return $matches[0];
}The same picture quoted twice goes in once ($byAttachmentId).
The reply editor stores a pasted screenshot as a data: image, and Gmail and Outlook won't show a data: image in a received email. Each one becomes an inline part:
$body = preg_replace_callback(
'/src=(["\'])data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+\/=\s]+)\1/i',
function ($m) use (&$inlineAttachments, &$cidCounter, $stamp) {
$bytes = preg_replace('/\s+/', '', $m[3]);
if (base64_decode($bytes, true) === false) {
return $m[0];
}
// ... add ['contentType' => $m[2], 'contentBytes' => $bytes, 'contentId' => $newCid, 'isInline' => true]
return 'src="cid:' . $newCid . '"';
},
$body
);These aren't counted against the 2 MB thread budget: they are the analyst's own content, like an attachment.
After the fix, a live reply with a pasted screenshot arrived in Gmail showing an empty box where the picture should be, with the picture listed as an attachment underneath. It looked exactly like a broken cid: reference. It wasn't one, and it's worth recording how that was proved, because the same symptom will turn up again.
-
The sent copy was pulled back through the Gmail API: valid MIME, one
<img src="cid:inline_image_1_β¦">, a matchingContent-IDon aninlineimage part, and a complete PNG (IENDpresent,getimagesizefromstring()happy). -
The received copy (Gmail β Show original β Download) was identical in every way that matters. Gmail had re-encoded it and added a text part, but the
cidstill matched. - Isolation tests, each changing one thing, all displayed correctly: the real screenshot, the real reply's exact HTML, the real subject (so Gmail threaded it into the same conversation), and no width/height.
-
Outlook opened the downloaded
.emlperfectly. -
The answer was on screen all along: the broken messages were in Gmail's Spam folder. Gmail strips images from spam β it keeps the
<img>with its width and height, which is the empty box, removes thesrc, and lists the picture as an attachment. Report as not spam and it appears.
Why spam? The sending domain's SPF record didn't list Google's servers (spf=fail in the received headers, though DKIM passed). That's DNS, not FreeITSM β but it will do the same to your customers. If you send through a Google Workspace mailbox, make sure your domain's SPF includes include:_spf.google.com.
π Before hunting an email rendering bug, check which folder it landed in. And compare the received message, not only the sent one β the difference between them is the receiver's doing, not yours.
php tests/outbound-email-mime.php β 29 checks, against the real code and real data:
| # | Section | What it proves |
|---|---|---|
| 0 | Declaration order | Every top-level const in send_email.php is declared above the code that sends (added in 2.10.1 β run against 2.10.0 it fails and names INLINE_THREAD_BUDGET) |
| 1 | The builder | Right structure for each case; bytes identical; the injected Bcc refused; UTF-8 names and subjects encoded; Date/Message-ID only with envelope, well-formed and unique |
| 2 | A real quoted thread | Every stored picture becomes a cid: part, byte-for-byte the file on disk |
| 3 | Another ticket's file | Left as a link β with a positive control: the same link to this ticket's file is embedded |
| 4 | The real SMTP client | Sends to a fake server the test starts on 127.0.0.1: multipart/mixed, CC delivered, PDF identical, every picture inside, Date and Message-ID present |
| 5 | The 2 MB cap | A ticket over the cap: one picture embedded, the rest left as links |
| 6 | A pasted screenshot | A data: image becomes an inline part |
Run against the broken code, the test fails where it should: 0 of the thread pictures are converted, and the SMTP section cannot send at all. The Date/Message-ID check was confirmed to fail with the option switched off.
Beyond the test:
-
The inbound side is untouched. The reading pane's responses for six inbound emails (22 pictures and files, all three providers) were recorded before and after: byte-for-byte identical. The recording has to save and restore
is_read, because opening an email marks it read β the first "before" snapshot differed from itself for that reason. - Live, from a Gmail mailbox: the attached PDF arrived, and the pasted screenshot displayed inline once the message was moved out of the Spam folder (see section 4).
- Live, 2.10.1, all three providers, through the real endpoint: nine numbered emails β per provider, a reply quoting a thread picture, a plain reply, and a forward with a thread picture, a pasted screenshot and an attached file. All nine arrived. The same tickets on 2.10.0 failed every picture case with the reporter's exact error, and sent nothing.
send_email.php sends the moment it is loaded, so the test evals only the functions (from getMailboxForTicket() down) and then the file's top-level constants. That means the test never runs the file in the server's order β which is how 2.10.0 passed every check while failing in production. Section 0 reads the order from the source to make up for it. If you add a constant, put it at the top; if you add a send path, drive it through the real endpoint as well.
Before 5.3.0 the system sender - ssSendSystemEmail() in includes/self_service_email.php, used for password resets, training reminders, task emails, the equipment report and more - took no files. Some installs cannot be reached from the internet, so a "download" link in an email opens nowhere there: the report has to travel in the email.
The whole emailed-reports feature - the settings, the download link's life from create to tidy-up, the table, behaviour before Database Verification and the tests - is in Emailed reports - Developer Guide. User guide: Emailed reports.
ssSendSystemEmail(PDO $conn, string $to, string $subject, string $htmlBody,
string $route = 'portal', array $attachments = []): bool
$attachments = [['name' => 'what-if.pdf', 'mime' => 'application/pdf', 'content' => $rawBytes]];The new argument is last and optional, so every existing caller is unchanged and still sends plain text/html. The files are checked and turned into the same Graph-shaped $parts list this page describes (section 1) by ssSystemEmailAttachmentParts(), so nothing new was written per provider:
| Provider | How the files go |
|---|---|
| Microsoft 365 |
ssSystemEmailGraphMessage() adds message.attachments (#microsoft.graph.fileAttachment, base64 contentBytes); no key at all when there are none |
| Gmail |
gmailSendEmail(..., $parts) - mimeBuildMessage() makes multipart/mixed
|
| SMTP |
imapSmtpSend(..., $parts) - the same builder |
Rules (ssSystemEmailAttachmentParts(), which throws InvalidArgumentException with a sentence fit to show; ssSendSystemEmail() then returns false and the send log says why):
-
3 MB in total (
SYSTEM_EMAIL_ATTACH_MAX_BYTES), at most 10 files.β οΈ Not 10 MB: Graph refuses a sendMail request over 4 MB and base64 adds a third, so 3 MB is the most that sends on every provider. A bigger cap would fail only on Microsoft 365. Past it needs Graph upload sessions. - File names:
ssAttachmentFilename()- no folder part, no control characters (so no CR/LF), no quotes or backslashes, at most 150 characters with the extension kept. - Types: a small allow-list (
SYSTEM_EMAIL_ATTACH_TYPES: PDF, CSV, text, PNG, JPEG, XLSX, DOCX); anything else goes asapplication/octet-stream.
For a page that builds a PDF in the browser (assets/js/pdf-writer.js) - first user: the "what if" report before deleting a directory source.
<script src="../../assets/js/email-report.js"></script>const r = await emailReportToMe({
subject: 'What if: delete directory source "Contoso AD"',
html: reportHtml, // the HTML version of the report, for the body (optional)
filename: 'what-if-contoso-ad.pdf',
pdf: doc // a pdf-writer document, Blob, ArrayBuffer or Uint8Array
});
showToast(r.ok ? r.message : r.error, r.ok ? 'success' : 'error');
// r = { ok: true, sentTo, delivered: {body, attachment, link}, message } | { ok: false, code, error }It never rejects; message and error are translated (common.email_report.*). It posts to api/system/email_report.php, whose rules are the point:
- any signed-in analyst, but it sends only to that analyst's own address - there is no recipient field, so it cannot be used as a relay (a
toin the request is ignored); - POST with the CSRF token; PDF only (
%PDF-and.pdf); 3 MB; - logged in the email send log as route
report_to_self; - error codes:
not_signed_in,bad_request,not_pdf,too_large,no_email,no_mailbox,send_failed.
What the email carries is not the caller's choice. System -> Emailed reports ticks any of In the body / As an attachment / As a download link (default body + attachment; at least one; links last 1, 7 or 30 days). Always pass the PDF and, when there is one, the HTML. If the only way ticked cannot carry the report (no HTML sent, or links not set up yet) the PDF is attached instead, so the report still arrives.
includes/report_downloads.php, table report_downloads.
- Token: 32 random bytes; only its SHA-256 is stored, looked up by hash and compared again with
hash_equals(). - The PDF is stored as
uploads/report-downloads/<32 hex>.bin- a random name, the folder denied to the web byuploadPrepareDir(); onlyapi/system/report_download.php?t=reads it. - That endpoint: not signed in -> sign in, then back to the link (a 15-minute
freeitsm_report_returncookie thatindex.phpreads; only a 64-hex token, fixed destination); another analyst -> 403; unknown 404; expired / revoked 410; the file is sent withContent-Disposition: attachment,nosniff,private, no-store. -
Audit: every create, download, refusal (with the reason), revoke and tidy-up is a
system_logsrow, typereport_download, with analyst, IP address and browser. System -> Emailed reports shows the recent ones. - The scheduled job
report_downloads_tidy(daily) deletes the files of expired and revoked links (row kept,file_deleted_atset), removes rows 90 days after expiry and deletes stray files. - Before Database Verification has added the table,
reportDownloadsReady()is false: the link option is skipped, everything else works, and nothing errors. - Administrators see every link and can Revoke one on System -> Emailed reports (
api/system/emailed_reports.php). A warning under the link tick shows when the install's address (publicBaseUrl()) is localhost, private or unset.
Tested by tests/system-email-attachments.php (fake SMTP server for the real sends; the endpoints over HTTP on a test install).
-
"Code that looks like it handles a case" is where bugs hide.
buildEmailMessage()calledprocessInlineImages(), so everyone assumed Microsoft embedded thread pictures. The pattern inside matched nothing. Count real matches before believing a converter works. -
A file saved to the ticket is not a file sent. If you add another send path, feed it the same
$partslist; don't let the ticket record something the email didn't carry. - The Graph 4 MB limit applies to the whole request. Anything that adds bytes to every reply needs a budget.
-
Only SMTP gets
envelope. Gmail stamps its ownDateandMessage-ID. - An empty box in Gmail may be Spam, not you. See section 4.
-
A top-level
constis not hoisted. In an endpoint, declare it above the working code, never beside the function that uses it. A test that loads only the functions cannot tell the difference.
- Replies with a picture in the thread failed to send β the 2.10.0 fault
- Reply attachments never reached the customer β the bug write-up
- Basic IMAP mailboxes
- Bugs resolved