Sending emails with attachments via ad-hoc tasks

I came across an interesting problem the other day. We had changed a service that sends out a system email with a PDF attachment to run in an ad-hoc task calling the custom event AdhocTasks.sendBackgroundEmail using $createTask() instead of calling the core $sendEmail() method. This caused the PDF to be corrupted.

Looking into the issue we saw that event_args in the psys_taskmanager_ad_hoctask table looked similar to this:

{
“to”: [
[email protected]
],
“locale”: “de_DE”,
“template”: “myCoolPdfSendingEmailTemplate”,
“attachments”: [
{
“name”: “foobar_20230727115527.pdf”,
“type”: “application/pdf”,
“binary”: “JVBERi0xLjQKJeLjz9MKMiA[…]g==”
}
]
}

The adhoc task manager then deserialised the parameters and called the EmailService to send the mail. The problem is that the “binary” value is now not binary but a base64-encoded string. When adding the attachment to the mail it gets base64-encoded again and that causes the file to be (obviously) incorrect.

Our solution was to implement an interceptor method at the onPrepareEmailSendArguments interception point that calls an event handler in the template to binaryDecode the variable value. Alternatively we could address this issue in the sendBackgroundEmail event that is called by the task. I wonder if this should be handled in Preside directly. What do you think?

1 Like

Yeah, an interesting problem. All that serializing and deserializing will also have a memory impact. Using local file system is a no go, but perhaps some kind of configurable storage provider for email attachments might be a way to go here. That way we can store paths and get a local path if the provider supports it for much more efficient sending of attachments.

We’d need our own cleanup logic though for attachments that are dynamic and short-lived (i.e. destroy after send).

1 Like

Is there a reason why the PDF is generated at this stage? Could it not be the system email’s job to obtain the PDF based on simple parameters passed?

1 Like

Could probably be done, yes.