Skip to content

Instantly share code, notes, and snippets.

@multivoltage
Last active April 24, 2025 07:12
Show Gist options
  • Save multivoltage/20cee6fde8db2efe22ac08a942ae0bf8 to your computer and use it in GitHub Desktop.
Save multivoltage/20cee6fde8db2efe22ac08a942ae0bf8 to your computer and use it in GitHub Desktop.
helper function to send email with attachment using AWS ses
import {
SendEmailCommand,
SendEmailCommandInput,
SendRawEmailCommand,
SendRawEmailCommandInput,
SendRawEmailRequest,
SESClient,
} from "@aws-sdk/client-ses";
export class RawMessageDataBuilder {
private msg = "";
constructor({
to,
fullname,
email,
phone,
city,
motivation,
role,
}: {
fullname: string;
email: string;
phone: string;
city: string;
motivation: string;
role: string;
to: string[];
}) {
this.msg = `From: <[email protected]>
To: ${to.join(",")}
Subject: Job Application - ${role} - ${fullname}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="NextPart"
--NextPart
Content-Type: text/html; charset=us-ascii
<body>
<p>Fullname: ${fullname}</p>
<p>Email: ${email}</p>
<p>Phone: ${phone}</p>
<p>Role: ${role}</p>
<p>Motivation: ${motivation}</p>
<p>City: ${city}</p>
</body>
`;
}
appendFile(base64String: string, fileName: string, mimeType: string) {
this.msg += `--NextPart
Content-Type: ${mimeType};
Content-Disposition: attachment; filename="${fileName}"
Content-Transfer-Encoding: base64
${base64String}
`;
}
build() {
if (!this.msg.endsWith("--NextPart--")) {
this.msg += `--NextPart--`;
}
return this.msg;
}
}
// example usage
function sendEmail(){
const buffer = fs.readFileSync("./file.pdf");
const fileBase64Cv = buffer.toString("base64");
builder.appendFile(fileBase64Cv, originalFilename, mimetype);
const builder = new RawMessageDataBuilder({
city,
email,
fullname,
motivation: message,
phone,
role: jobTitle,
to: addresses,
});
const params: SendRawEmailCommandInput = {
RawMessage: {
Data: Buffer.from(builder.build(), "utf8"),
},
Source: "[email protected]" /* required */,
};
const command = new SendEmailCommand(params);
const sesClient = new SESClient({
region: "eu-west-1",
credentials: {
accessKeyId: "xxx",
secretAccessKey: "yyy",
},
});
return await sesClient.send(command);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment