Send emails from your SvelteKit application using Nodemailer and Brevo


First, let's start with installing the required packages. Open your terminal and run:
npm i nodemailer nodemailer-brevo-transportBefore we proceed, you'll need to set up an API key with Brevo:
API key and add it to your project's .env file for safekeeping: # In your .env file
VITE_BREVO_API='your-brevo-api-key-here'Ensure you replace 'your-brevo-api-key-here' with your actual
Brevo APIkey.
Create a file named sendMail.js in your project's lib folder. This file will house our email-sending logic.
First, import the environment variable where we stored our Brevo API key:
// sendMail.js
let brevoAPI = import.meta.env.VITE_BREVO_API;Then, import Nodemailer and the Brevo transport module:
import nodemailer from 'nodemailer';
import brevoTransport from 'nodemailer-brevo-transport';Set up the transporter object which Nodemailer will use to send emails:
const transporter = nodemailer.createTransport(new brevoTransport({
apiKey: brevoAPI
}));Now, let's write a function to handle the email sending process:
export async function mailPost(request) {
// Extract the necessary details from the request body
const { user_name, user_email, user_detail } = request.body;
// Configure your mail options
const mailOptions = {
from: user_email, // Sender's email
to: 'yourMail@gmail.com', // Replace with your email
subject: `New message from (${user_name})`,
html: user_detail, // For HTML body content
text: user_detail // For plain text body content
};
// Attempt to send the email
try {
await transporter.sendMail(mailOptions);
return {
status: 200,
body: 'Email sent successfully'
};
} catch (error) {
console.error(error);
return {
status: 500,
body: 'Failed to send email. Please try again'
};
}
}Finally, integrate the mailPost function within your SvelteKit endpoint +page.server.js, to handle form submissions:
// In your +page.server.js
// Logic to handle form validation and submission...
if (!formData.valid) {
return message(formData, {
text: 'Please correct your form submission.',
status: 400
});
} else {
const response = await mailPost({ body: { user_name, user_email, user_detail } });
// Check the response status and act accordingly
if (response.status === 200) {
return message(formData, {
text: 'Your opinion has been received. Thank you!',
status: 200
});
} else {
console.log('response: ', response);
return message(formData, { text: response.body, status: response.status });
}
} 
Improve caching and performance in SvelteKit by importing images from src/lib instead of static. Learn why and how this approach works.

Learn how to use the GitHub REST API to read and display files like sitemap.xml in your SvelteKit application. A step-by-step guide for developers.