Created
October 25, 2024 00:36
-
-
Save aloysb/f3c5b21b76dcf112ff871996225a6016 to your computer and use it in GitHub Desktop.
AWS and Mailpit mailing for prod and dev envs.
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 { render } from "@react-email/components"; | |
import nodemailer from "nodemailer"; | |
import { EmailVerificationOTP } from "./templates/EmailVerificationOTP"; | |
import aws from "@aws-sdk/client-ses"; | |
import { defaultProvider } from "@aws-sdk/credential-provider-node"; | |
import Mail from "nodemailer/lib/mailer"; | |
// AWS | |
const provider = defaultProvider({ | |
profile: "profile", | |
}); | |
const ses = new aws.SES({ | |
apiVersion: "2010-12-01", | |
region: "us-east-1", | |
credentials: provider, | |
}); | |
// Transporters | |
const transporters = { | |
prod: nodemailer.createTransport({ | |
SES: { ses, aws }, | |
}), | |
// Using mailpit for local development | |
dev: nodemailer.createTransport({ | |
host: "mailpit", | |
port: 1025, | |
secure: false, | |
}), | |
}; | |
// Eventually the email should be moved as a function argument to improve reusability | |
const emailHtml = await render(<EmailVerificationOTP otp="123456" />); | |
const options = { | |
from: "[email protected]", | |
to: "[email protected]", | |
subject: "hello world", | |
html: emailHtml, | |
}; | |
async function sendMail(options: Mail.Options) { | |
const isDev = process.env.NODE_ENV === "development"; | |
return isDev | |
? transporters.dev.sendMail(options) | |
: transporters.prod.sendMail(options); | |
} | |
// Send the email and add logging | |
try { | |
const info = await sendMail(options); | |
console.log("Email sent successfully:", info); | |
} catch (error) { | |
console.error("Error sending email:", error); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment