Send Personalized Emails using Gemini API, SendGrid and Node.js
Time to read: 6 minutes
Send Personalised Emails using Gemini API, SendGrid and Node.js
Sending generic, one-size-fits-all emails is no longer an effective strategy as it fails to resonate with the recipient on a personal level. With the use of generative AI you can accelerate the process of crafting and sending personalised emails at scale.
Large language models, such as Gemini pro, allow you to generate highly contextual and natural-sounding text tailored to each recipient's unique profile. This approach saves time and ensures a level of personalization that would be nearly impossible to achieve manually.
In this tutorial, you will build a simple application that uses the Gemini pro model to generate personalised emails based on your prompt, allows you to edit the email before finalising it and use SendGrid’s email delivery system to send the email. You will use Node.js for server-side logic and React.js for a simple frontend.
Prerequisites
In order to follow along with this tutorial, you will need the following:
- A SendGrid account - Sign up here to send up to 100 emails per day completely free of charge
- Node.js Installation
Setting up the project
Start by creating a minimal React.js project using nano-react-app
with the following command:
Change the working directory to your new React project, ai-email-dashboard,install dependencies with npm install
and run the application to make sure everything is fine:
Building the Frontend
Construct a basic user interface in your App.jsx file, that has a heading that says Dashboard, an input box for writing the prompt, a Generate button, a preview section that displays the generated email and allows you to edit it, and a Send Email button:
You can style this React interface, using an external stylesheet. Create a file index.css and add this code:
To apply this css styling, add an import in the index.js file in the /src directory:
To make sure the application is running, go to http://localhost:5173/ and it should look like this:
Setting up an Express Backend
You can create a simple backend server using Express.js
for creating APIs and handling server-side logic. Start with installing these dependencies:
nodemon
: It is a development utility that automatically restarts your Node.js application whenever you make changes to the code.dotenv
: This package allows you to load environment variables from a .env file, keeping sensitive information like API keys out of your codebase.nodemailer
: This package simplifies sending emails from your Express.js backend.@google/generative-ai
: To use the Gemini API in your own application, you need to install theGoogleGenerativeAI
package for Node.js
Start by creating a new file named server.js in the root directory of your application and add:
This code sets up a basic Express.js server with functionalities for parsing incoming data (JSON and URL-encoded forms) and handling CORS. It also allows you to load environment variables for secure configuration and starts the server on the port 8000.
Start the the backend server with the following command:
Once the server starts successfully, you should see 'Listening to Port 8000' in your terminal.
Obtain the Gemini API Key
To use the Gemini API, you first need to obtain the API key from https://aistudio.google.com/app/apikey
Once you have it, store it securely in a .env file in the root directory. Create a .env if you don’t have one and add:
Using Gemini API in your Backend
Add this in your server.js to access the Gemini API key and import the GoogleGenerativeAI
package:
Create a /generate
route handler, in server.js, to generate text using Gemini:
This code defines a route handler for /generate
that listens for POST requests. When a request arrives, it retrieves the prompt sent from the frontend in the request body.
Notice the prompt is modified before sending it to the generative model. It specifies that the first line of the generated text should become the subject line of the email, and the remaining text should form the body. This will simplify the process of separating the subject and body later.
The code uses the gemini-pro
generative model to generate text based on the prompt. Finally, the generated text is extracted and sent back to the frontend as a JSON response with a key named text
.
Make sure your express server is running and use Postman to test the /generate
API route:
In the query parameters, set the “prompt” key with your prompt as the value, and send a post request to http://localhost:8000/generate. The output should be the text generated by Gemini AI based on your prompt.
Fetching AI Generated Text from the Backend
In your App.jsx create three state variables, subject
and body
for our email, and prompt
to store the prompt. Add this right above the return
function:
Since the state variables subject
and body
already hold the initial values, you can directly set the value attribute of the input elements to these variables, and set an onChange
listener to detect changes and update the state variables:
Now, define a new function called generateEmail
, right before the return function. This function will be responsible for fetching data from the /generate
API:
This function interacts with a backend API to generate an email based on the provided prompt and updates the component's state with the retrieved subject and body content
Set an onClick listener for the Generate button to trigger the generateEmail()
function
To test the application, make sure your React application and Node.js server are running concurrently, enter a prompt and click the Generate button:
The app should display the generated text in the input areas and allow the user to edit the text. The final step is to use SendGrid to deliver the email.
Delivering the Email with SMTP Server
SMTP stands for Simple Mail Transfer Protocol. It is a standardised protocol used for sending and receiving email messages between email servers. For your email generator to work seamlessly, you need a reliable email delivery service. Twilio SendGrid is an excellent choice for this purpose.
Obtaining the SendGrid API key
- Go to the SendGrid website.
- For this tutorial, select a free plan, provide required details, and sign up!
After signing up, navigate to the Dashboard, and on the left sidebar go to: Settings > Sender Authentication.
Perform the sender authentication (single sender verification in this case) by verifying your email address. After verification, create a new sender by filling in the required details. This is the email that will be used by the SMTP Server to send emails.
Go to the API Keys section in your SendGrid Dashboard by heading to the settings tab on the left-hand side and clicking API Keys.
Click the blue “Create API Key” button on the top right and a form will appear.
Set a name for your API key and click the blue Create & View button. Copy your API key and store it in the .env file in your root directory:
Building the /send-email Route
A transporter
is a Nodemailer object that acts as a bridge between your Node.js application and the SendGrid Email service. In your server.js, right above the /generate
route, add a transporter:
Below this, write a new route called /send-email
:
This route retrieves the email details (subject and body) from the request body, uses the configured transporter to send the email, and sends a response back to the client indicating success or failure.
To keep things simple in this tutorial, the recipient's email address is directly entered in the code. However, you might have noticed the email list option in the user interface, located above the Send button. With some additional coding and logic, you can implement a feature that allows users to select the recipient's email from a list instead of having it hardcoded.
Final Step
The last step is to send the body and subject to the /send-email
route on your server for the email to be delivered. In your App.jsx, right above the return function, create a function called sendEmail()
:
This code defines a function sendEmail
that sends the email contents if subject
and body
are provided. It prepares the email data in JSON format and sends a POST request to the /send-email route.
Don’t forget to add an OnClick
listener in the Send Email button to trigger the sendEmail
function:
Test the application by clicking on the Send Email button. If the email is sent successfully, your server's terminal should display a confirmation message:
Conclusion
Congratulations! You have successfully built an application that leverages a Large Language Model, and SendGrid to generate and send personalised emails.
The source code for this project can be found here: AI Email Dashboard
What’s next?
- Add a feature to send email to multiple recipients.
- Improve upon the design of the application.
- Implement analytics such as open rates, click-through rates, and conversion rates.
Avinash Prasad is a Software Developer and Content Creator. He has a passion for simplifying complex technical topics, making them accessible to a wide audience. He is the host of DevStories podcast . He can be reached via email and Twitter .
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.