I am using the NPM package postal-mime to process inbound emails through cloudflare workers. Similar code to on this guide.
https://docs.emailengine.app/how-to-parse-emails-with-cloudflare-email-workers/
The link states this about attachments.
Attachment support.
PostalMime parses all attachments into Uint8Array objects. If you want to process the contents of an attachment as a regular string (which makes sense for textual attachments but not for binary files like images), you can use the TextDecoder class for it.
const decoder = new TextDecoder('utf-8');
const attachmentText = decoder.decode(email.attachments[0].content);
Everything is working as expected when I send an email with a CSV attachment, I can read the CSV and send the data to my server.
However I now have a 3rd party sending the CSV inside a zip file.
The data that arrives at my server is not a valid zip file, presumably since it has been decoded into a text format rather than kept as binary. The guide specifically states this doesn’t make sense for binary files.
If I send the raw email.attachments[0].content to the server all I get is an empty array.
How can I process this Uint8Array object into a form that will allow me to post to my server, then decode it as a valid binary zip file?
import PostalMime from 'postal-mime';
export default {
async email(message, env, ctx) {
const parser = new PostalMime();
const email = await parser.parse(message.raw);
console.log('Subject', email.subject);
console.log('HTML', email.html);
console.log(message);
const webhookUrl = 'https://example.com/webhook';
var attach;
var attach_binary;
email.attachments.forEach((attachment) => {
let decoder = new TextDecoder('utf-8');
console.log('Attachment', attachment.filename,
decoder.decode(attachment.content));
if(attachment.mimeType == 'application/zip'){
attach_binary = '';//DO SOMETHING HERE
}else{
attach = decoder.decode(attachment.content);
}
});
const webhookPayload = JSON.stringify({
subject: email.subject,
sender: message.from,
email_html: email.html,
email_text: email.text,
email: message.to,
csv: attach ,
csv_binary: attach_binary
});
try {
const response = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: webhookPayload,
});
if (response.ok) {
console.log('Webhook request successful');
} else {
console.error('Webhook request failed:', response.status);
}
} catch (error) {
console.error('Error sending webhook request:', error);
}
},
};