Velo Tutorial: Send Emails Using the SendGrid npm Package
- If you want to work with a copy of the example site, you'll need to create your own SendGrid account and save your email address and the SendGrid API key in the Secrets Manager (see detailed instructions below).
- You can also integrate your Wix site with SendGrid using the Fetch API.
Overview
- Create a SendGrid account.
- Store the SendGrid API key and your sender email address in the Secrets Manager.
- Add the SendGrid npm package to your site.
- Add a custom form to your page for getting the recipient email address and email text from site visitors.
- Write code in a backend web module to get the API key from the Secrets Manager and send an email using an npm package function.
- Write page code to use the imported backend function to send an email, using the email data entered in the form fields.
Step 1: Create an Account with SendGrid
- In the SendGrid site, navigate to the left menu.
- Go to Settings > Sender Authentication and verify your email address.
- Go to Settings > API Keys and generate an API key.
- Copy the key from your dashboard and store it in the Secrets Manager in your Wix site (see the next step).
Step 2: Set Up the Site
- Store secrets in the Secrets Manager.
- Add the SendGrid npm package to your site.
- Add elements to your page.
Step 2a: Store Secrets in the Secrets Manager
- In the Velo Sidebar, select the Developer Tools
tab.
- Under the Security section, select Secrets Manager.
- In the top right, click Store Secret.
- Store both your SendGrid API key and the verified email address associated with your SendGrid account in a single secret. The secret should look like this:
- Make sure to name the secret: sendGridSecret.
- Replace <my-sendgrid-api-key> with the value of your API key surrounded by quotation marks.
- Replace <my-verified-sender-email> with your email address surrounded by quotes.
- Your secret value will look something like this:
1{
2 "key": "AB.CdPEfg1HIJk-LMnoPq2R3s.T4uVwxyZAbcd567eF8fghIjKL9mN",
3 "senderEmail": "janedoe@example.com"
4}
Later you'll use the Secrets API to extract the secret and use it securely in your code (see Step 3b).
Step 2b: Add the SendGrid npm Package
- In the Velo Sidebar, click the Code Files
tab.
- In the Packages section, hover over npm, click the plus icon
and select Install package from npm.
The Package Manager opens. - In the search bar, enter 'sendgrid'.
- Next to the @sendgrid/mail package, click Install.
You'll see the package under npm in the Packages section of your Code Files tab in the Velo Sidebar.
Step 2c: Add Page Elements
- Input elements for the recipient's email and subject line
- Text box for the email body text
- Submit button for sending the email
- Text element for displaying success and error messages

Step 3: Write Backend Code in the sendEmail.jsw Web Module
- Extract the SendGrid API key from the Secrets Manager.
- Set the API key in SendGrid.
- Send an email using a SendGrid npm package function.
Step 3a: Add a Web Module
- In the Velo Sidebar, select the Code Files
tab.
- In the Backend section, click Add web module.
- Name the file sendEmail.jsw.
The file will open in the Code Panel. Place the code below in the file.
Step 3b: Import Modules
1import sgMail from "@sendgrid/mail";
2import wixSecretsBackend from 'wix-secrets-backend';
Understanding the Code
Line 1: Import the sgMail
module containing the functions you need from the npm package that we added to our site.
Line 2: Import the wix-secrets-backend
module for extracting secrets from the Secrets Manager.
Step 3c: Extract and Set the API Key
In our sendEmail
function, we start by getting the SendGrid API key and sender email address that we saved in the Secrets Manager, and setting the API key to enable usage of the SendGrid service.
1export async function sendEmail(recipient, subject, body) {
2
3 const sendGridSecret = JSON.parse(await wixSecretsBackend.getSecret('sendGridSecret'));
4 const key = sendGridSecret.key;
5 const senderEmail = sendGridSecret.senderEmail;
6
7 sgMail.setApiKey(key);
Understanding the Code
Line 1: Declare and export the asynchronous sendEmail
function for sending the email.
Line 3: Get the SendGrid secret from the Secrets Manager using the getSecret
function and save it in a variable named sendGridSecret
. The JSON.parse
function converts the JSON string into an object.
Line 4: Save the API key extracted from the secret as a variable called key
.
Line 5: Save the sender email extracted from the secret as a variable called senderEmail
.
Line 7: Set the API key using the setApiKey()
function from the SendGrid npm module.
Step 3d: Send an Email
While still inside our sendEmail()
function, we call the npm package send()
function to send the email.
1const msg = {
2 from: senderEmail,
3 to: recipient,
4 subject: subject,
5 text: body
6 };
7
8 try {
9 return await sgMail.send(msg);
10 } catch (error) {
11 console.error('Error sending the email: ' + error.message);
12 return false;
13 }
14}
Understanding the Code
Lines 1-6: Set the data for the email to be sent, such as the recipent's email address and the text of the email body. The sender email was extracted from the Secrets Manager and the rest of the information is entered by site visitors on the frontend via input elements.
Lines 8, 10: Use try
and catch
to catch any errors.
Line 9: Call the send()
npm package function to send the email with the email data passed to the function.
Step 4: Write Page Code in the Frontend
In our page code on the frontend of our site, we do the following:
- Get email information such as the recipient's email address and email text from site visitors via the custom form fields.
- Validate the form fields.
- Use the
sendEmail()
function imported from the backend with the form field values to send an email. - Show a success or error message.
Step 4a: Setup
First we import the function we need from the backend and set a global constant.
1import { sendEmail } from 'backend/sendEmail.jsw';
2const SUCCESS_CODE = 202;
Understanding the Code
Line 1: Import the sendEmail()
function that we created in the backend so that we can use it in our page code.
Line 2: Set a SUCCESS_CODE
constant to 202
. We'll use it to check whether the sendEmail()
function request was successful.
Step 4b: Validate the Form Fields
We added the checkFormFields()
function to make sure all form field input values are valid before sending an email.
1function checkFormFields() {
2 return $w('#toEmail').validity.valid && $w('#subject').validity.valid && $w('#emailContent').validity.valid;
3}
Understanding the Code
Line 1: Declare the function that we'll call in the onReady()
function.
Line 2: If all input values are valid, return true
. If one is not valid, return false
.
Step 4c: Clear the Form Fields
We added the clearFields()
function to reset the form fields following a successful email transmission.
1function clearFields() {
2 $w('#toEmail').value = '';
3 $w('#subject').value = '';
4 $w('#emailContent').value = '';
5
6 $w('#toEmail').resetValidityIndication();
7 $w('#subject').resetValidityIndication();
8 $w('#emailContent').resetValidityIndication();
9}
Understanding the Code
Line 1: Declare the function that we'll call in the onReady()
function.
Lines 2-4: Clear the input values.
Lines 6-8: Reset the inputs' visual validity indications. Some elements have a visual cue, such as a red outline, that indicates when the current value isn't valid. This function clears any indications.
Step 4d: Show Success and Error Messages
We added the showMessage()
function to temporarily show a success or error message following an attempt to send an email.
1function displayMessage(message) {
2 $w('#messageText').text = message;
3 $w('#messageText').show();
4 $w('#messageText').hide('fade', { delay: 5000 });
5}
Understanding the Code
Line 1: Declare the function that we'll call in the onReady()
function.
Line 2: Set the message text with the text passed to the function.
Line 3: Show the success or error message.
Line 4: Hide the message after 5 seconds.
Step 4e: Send the Email when the Form Is Submitted
- Check whether all form field values are valid.
- If they're valid, send the email with the values extracted from the form inputs. If the form fields aren't valid, show an error message.
- If the email transmission request is successful, clear the form fields and display a success message. If the request fails, show an error message.
1$w.onReady(function () {
2 $w('#sendButton').onClick(async () => {
3 const passedValidations = checkFormFields();
4 if (passedValidations) {
5 const emailResult = await sendEmail(
6 $w('#toEmail').value,
7 $w('#subject').value,
8 $w('#emailContent').value);
9 if (emailResult[0].statusCode === SUCCESS_CODE) {
10 clearFields();
11 displayMessage('Email was sent');
12 } else {
13 displayMessage('Error sending email, please verify your SendGrid account details.');
14 }
15 } else {
16 displayMessage('Validation error, please review your input fields.');
17 }
18 })
19});
Understanding the Code
Line 1: We added our code to the onReady()
function, which runs when the page loads.
Line 2: When a site visitor clicks the Send button, run the following code.
Lines 3-4: Check if all input field values are valid. If not, see Lines 15-16. If they are, run the following code.
Lines 5-8: Run the sendEmail()
function that we imported from the backend with the field input values as parameters, and assign the result to a variable.
Line 9: Check if the email transmission request was successful (returned a 202
status code). If not, see Lines 12-13. If yes, run the following code:
Line 10: Clear the input values and reset validity indications.
Line 11: Display a message to let site visitors know that the email was sent.
Lines 12-13: If the email transmission request was not successful, display an error message.
Lines 15-16: If not all input fields are valid, display an error message.
Learn More
Example Code
Backend Code in sendEmail.jsw File
1import sgMail from '@sendgrid/mail';
2import wixSecretsBackend from 'wix-secrets-backend';
3
4export async function sendEmail(recipient, subject, body) {
5
6 const sendGridSecret = JSON.parse(await wixSecretsBackend.getSecret('sendGridSecret'));
7 const key = sendGridSecret.key;
8 const senderEmail = sendGridSecret.senderEmail;
9
10 sgMail.setApiKey(key);
11
12 const msg = {
13 from: senderEmail,
14 to: recipient,
15 subject: subject,
16 text: body
17 };
18
19 try {
20 return await sgMail.send(msg);
21 } catch (error) {
22 console.error('Error sending the email: ' + error.message);
23 return false;
24 }
25}
Frontend Page Code
1import { sendEmail } from 'backend/sendEmail.jsw';
2const SUCCESS_CODE = 202;
3
4$w.onReady(function () {
5 $w('#sendButton').onClick(async () => {
6 const passedValidations = checkFormFields();
7 if (passedValidations) {
8 const emailResult = await sendEmail($w('#toEmail').value, $w('#subject').value, $w('#emailContent').value);
9 if (emailResult[0].statusCode === SUCCESS_CODE) {
10 clearFields();
11 displayMessage('Email was sent.');
12 } else {
13 displayMessage('Error sending email, please verify your SendGrid account details.');
14 }
15 } else {
16 displayMessage('Validation error, please review your input fields.');
17 }
18 })
19});
20
21function checkFormFields() {
22 return $w('#toEmail').validity.valid && $w('#subject').validity.valid && $w('#emailContent').validity.valid;
23}
24
25function clearFields() {
26
27 $w('#toEmail').value = '';
28 $w('#subject').value = '';
29 $w('#emailContent').value = '';
30
31 $w('#toEmail').resetValidityIndication();
32 $w('#subject').resetValidityIndication();
33 $w('#emailContent').resetValidityIndication();
34}
35
36function displayMessage(message) {
37 $w('#messageText').text = message;
38 $w('#messageText').show();
39 $w('#messageText').hide('fade', { delay: 5000 });
40}