Sending Emails with Astro v3 and Nodemailer
Writed by Moncef in 05/07/2023.
This post focuses on how to send emails in an Astro v3 project using TypeScript and Nodemailer.
Setup
Initialize Astro project and install dependencies
Terminal
Install Packages
Install Nodemailer for sending emails and Zod for validation
Terminal
Environment Variables
Create a .env file and add your credentials see this to learn how to get it :
.env
Email Utility Function
Create a file src/lib/utils.ts and add:
src/lib/utils.ts
Building the Validation Function
Let's start by defining our validation function using Zod. Create a new file under src/lib/utils and add the following code:
src/lib/utils.ts
Form UI
Update src/pages/index.astro to handle the form submission we can start by building the ui:
src/pages/index.astro
Building the contact form logic
After that, we can start building the contact form logic. Place the following code at the top of src/pages/index.astro:
src/pages/index.astro
The last steps
While nodemailer can only run in a Node.js runtime, Astro is a static site generator (SSG) by default. To switch Astro to server-side rendering (SSR) mode, you can run the following command in a Node.js environment:
Terminal
However, if you wish to deploy it serverlessly on Vercel, use this command instead:
Terminal
For more information on this subject, check out the Astro SSR guide.
That's it! You can now easily send emails directly from your Astro project using Nodemailer.
Happy coding!