Skip to content

Instantly share code, notes, and snippets.

@n05la3
Created March 22, 2023 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n05la3/446ae67182bdcf64c97b356adeb929d4 to your computer and use it in GitHub Desktop.
Save n05la3/446ae67182bdcf64c97b356adeb929d4 to your computer and use it in GitHub Desktop.
Email Templating With AWS SDK and EJS in a Node backend
import { join } from 'path';
import { SendEmailCommand, SESClient } from '@aws-sdk/client-ses';
import { renderFile } from 'ejs';
interface Template {
name: string;
data?: Record<string, any>
}
interface EmailOption {
to: string;
subject: string;
from: string;
template?: Template;
};
export class EmailService {
private readonly templatePath = join(__dirname, 'templates');
private readonly client: SESClient;
constructor() {
this.client = new SESClient({
region: 'my-aws-region',
credentials: {
accessKeyId: 'my-access-key-id',
secretAccessKey: 'my-access-key-id',
},
});
}
async send({
to
from,
subject,
text,
template,
}: EmailOption) {
const sendEmailCommand = new SendEmailCommand({
Destination: {
To: to,
},
Message: {
Body: {
...(template && {
Html: {
Charset: 'UTF-8',
Data: this.generateTemplate(template),
},
}),
},
Subject: {
Charset: 'UTF-8',
Data: subject,
},
},
Source: from,
ReplyToAddresses: [],
});
try {
await this.client.send(sendEmailCommand);
} catch (error) {
throw new Error(error);
}
}
async generateTemplate({ name, data }: Template) {
return renderFile(
join(this.templatePath, `${name}.ejs`),
data,
);
}
}
const emailService = new EmailService();
await emailService.send({
destination: {
To: 'john_doe@example.com'
},
from: 'noreply@dm.com',
subject: 'Welcome to Email templating with EJS',
template: {
name: 'welcome',
data: {
name: 'John Doe'
}
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
Welcome <%= name %>, it's nice to have you on board.
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment