Created
March 22, 2023 06:22
-
-
Save n05la3/446ae67182bdcf64c97b356adeb929d4 to your computer and use it in GitHub Desktop.
Email Templating With AWS SDK and EJS in a Node backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
} | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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