Send emails from your SvelteKit application using Nodemailer and Brevo

sveltekit email integration with nodemailer and brevo

Send emails from your SvelteKit application using Nodemailer and Brevo

sveltekit
nodemailer
brevo
email

Installation

First, let's start with installing the required packages. Open your terminal and run:

npm i nodemailer nodemailer-brevo-transport

Setting Up Brevo

Before we proceed, you'll need to set up an API key with Brevo:

  1. Visit Brevo's website and log in or sign up.
  2. Navigate to the API section and create a new API key.
  3. Copy the 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 API key.

Preparing the Email Utility

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';

Configuring the Transporter

Set up the transporter object which Nodemailer will use to send emails:

const transporter = nodemailer.createTransport(new brevoTransport({
  apiKey: brevoAPI
}));

Writing the Mail Sending Function

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: '[email protected]', // 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'
    };
  }
}

Integration with SvelteKit

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 });
    }
}