Attach PDF to email using Lambda + S3 + SES | by David Ambros | Dec, 2023
import { S3Client, GetObjectCommand } from “@aws-sdk/client-s3”;
const sesClient = new SESClient({ region: process.env.REGION });
const s3Client = new S3Client({ region: process.env.REGION });
const s3Bucket = process.env.PDF_HOLDER_BUCKET_NAME;
export const handler = async (event) => {
// …your logic here
await processAndSendEmail();
// …your logic here
};
async function processAndSendEmail() {
const pdfKey = ‘myPdfFileName.pdf’;
const senderEmail = ‘sender@example.com‘;
const recipientEmail = ‘recipient@example.com‘;
const subject = ‘Subject of the email’;
try {
//Fetch the pdf from S3
const s3Params = {
Bucket: s3Bucket,
Key: pdfKey
};
const s3Command = new GetObjectCommand(s3Params);
const s3Response = await s3Client.send(s3Command);
const pdfAttachment = {
filename: ‘myPdfFileName.pdf’,
content: s3Response.Body
};
//Create the email
const rawEmail = await createRawEmail(
senderEmail,
recipientEmail,
subject,
‘Body of your email’,
pdfAttachment);
//Send the email
const sesParams = {
RawMessage: { Data: Buffer.from(rawEmail) },
Source: senderEmail
};
const sesCommand = new SendRawEmailCommand(sesParams);
await sesClient.send(sesCommand);
} catch (error) {
console.error(`Error: ${error}`);
}
}
async function createRawEmail(sender, recipient, subject, bodyText, attachment) {
const boundary = ‘NextPart’;
const header = `From: ${sender}\n` +
`To: ${recipient}\n` +
`Subject: ${subject}\n` +
‘MIME-Version: 1.0\n’ +
`Content-Type: multipart/mixed; boundary=”${boundary}”\n\n`;
const body =
`–${boundary}\n` +
‘Content-Type: text/html; charset=us-ascii\n\n’ +
`${bodyText}\n\n` +
`–${boundary}\n` +
‘Content-Type: application/pdf;\n’ +
`Content-Disposition: attachment; filename=”${attachment.filename}”\n` +
‘Content-Transfer-Encoding: base64\r\n\r\n’ +
`${Buffer.from(await attachment.content.transformToByteArray()).toString(‘base64’)}\n\n` +
`–${boundary}–`;
return header + body;
}
Read more here: Source link
