> Portal Navigation: > > - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version. > - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages). > - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`). > - Top-level index of all portals: https://dev.wix.com/docs/llms.txt > - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt ## Resource: Send Emails Using the SendGrid npm Package ## Article: Send Emails Using the SendGrid npm Package ## Article Link: https://dev.wix.com/docs/develop-websites/articles/code-tutorials/wix-editor-elements/send-emails-using-the-send-grid-npm-package.md ## Article Content: # Velo Tutorial: Send Emails Using the SendGrid npm Package
>**Note:** > This tutorial and its steps are based on a Wix Editor site. You can adapt the steps for a Wix Studio site by using the equivalent [Wix Studio features](https://dev.wix.com/docs/develop-websites/articles/coding-with-velo/overview/about-coding-with-wix-studio.md#finding-your-way). This article describes how to integrate your Wix site with the [SendGrid service](https://sendgrid.com/) and send emails directly from your site. You'll need to add the [SendGrid npm package](https://www.npmjs.com/package/@sendgrid/mail) to your site to incorporate the SendGrid functionality. This tutorial is based on the SendGrid npm Integration [example site](https://www.wix.com/velo-examples/sendgrid-npm). You can open a copy of the [site's editor](https://editor.wix.com/html/editor/web/renderer/new?siteId=5494404c-1163-4c51-8bc2-bf8466a23e34&metaSiteId=1e3b3a34-4b1e-416c-abb9-334db84d0261&autoDevMode=true) and play around with the code. >**Notes** > * 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](https://dev.wix.com/docs/develop-websites/articles/workspace-tools/developer-tools/secrets-manager/about-the-secrets-manager.md) (see detailed instructions [below](https://support.wix.com/en/article/velo-tutorial-send-emails-using-the-sendgrid-npm-package#step-2a-store-secrets-in-the-secrets-manager)). > * You can also integrate your Wix site with SendGrid using the [Fetch API](https://www.wix.com/velo/reference/wix-fetch). ## Overview To set up your site to send emails with the SendGrid service, you'll need to perform the following steps: 1. Create a SendGrid account. 2. Store the SendGrid API key and your sender email address in the Secrets Manager. 3. Add the SendGrid npm package to your site. 4. Add a custom form to your page for getting the recipient email address and email text from site visitors.  5. 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. 6. Write page code to use the imported backend function to send an email, using the email data entered in the form fields. >**Note** > This tutorial describes how to use a custom form to get email data such as email addresses and body text from site visitors. You might have a different use case, such as constructing the emails yourself as a site admin. You might use email data stored in a database collection, enter the email data directly in your code, or use the custom form but on a [Dashboard page](https://support.wix.com/en/article/velo-working-with-dashboard-pages). In any case, you'll need to adjust your code to get the email data from its source and pass it to the [sendEmail()](https://dev.wix.com/docs/develop-websites/articles/code-tutorials/wix-editor-elements/send-emails-using-the-send-grid-npm-package.md) function. ## Step 1: Create an Account with SendGrid To use the SendGrid service on your Wix site, you'll need to create a [SendGrid account](https://signup.sendgrid.com/). The email address you verify in the account will be the sender address for the emails you send from your Wix site. Once you've created an account, do the following: 1. In the SendGrid site, navigate to the left menu. 2. Go to **Settings > Sender Authentication** and verify your email address. 3. Go to **Settings > API Keys** and generate an API key.  4. Copy the key from your dashboard and store it in the [Secrets Manager](https://dev.wix.com/docs/develop-websites/articles/code-tutorials/wix-editor-elements/send-emails-using-the-send-grid-npm-package.md) in your Wix site (see the next step).   ## Step 2: Set Up the Site To set up your Wix site, do the following: 1. Store secrets in the Secrets Manager. 2. [Add the SendGrid npm package to your site.](https://dev.wix.com/docs/develop-websites/articles/code-tutorials/wix-editor-elements/send-emails-using-the-send-grid-npm-package.md) 3. Add elements to your page. ### Step 2a: Store Secrets in the Secrets Manager For security purposes, it's best to store sensitive content such as API keys in the [Secrets Manager](https://dev.wix.com/docs/develop-websites/articles/workspace-tools/developer-tools/secrets-manager/about-the-secrets-manager.md).  1. In the [Code sidebar](https://dev.wix.com/docs/develop-websites/articles/coding-with-velo/overview/about-coding-with-wix-studio.md#ways-to-code-with-wix-studio), select the **Developer Tools** ![](https://d2x3xhvgiqkx42.cloudfront.net/12345678-1234-1234-1234-1234567890ab/0ca9e8ba-16ed-4cd8-a1e1-58d01c4420f7/2021/10/14/5526a3fb-4472-4c9e-9cf2-a7231343d9c6/c54e27bf-b090-4b15-adc0-6a437d141721.png)  tab.  2. Under the Security section, select **Secrets Manager**. 3. In the top right, click **Store Secret**. 4. 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 `` with the value of your API key surrounded by quotation marks. * Replace `` with your email address surrounded by quotes. * Your secret value will look something like this: ```json { "key": "AB.CdPEfg1HIJk-LMnoPq2R3s.T4uVwxyZAbcd567eF8fghIjKL9mN", "senderEmail": "janedoe@example.com" } ``` 5. Click **Save**. Later you'll use the [Secrets API](https://www.wix.com/velo/reference/wix-secrets-backend/getsecret) to extract the secret and use it securely in your code (see [Step 3b](https://dev.wix.com/docs/develop-websites/articles/code-tutorials/wix-editor-elements/send-emails-using-the-send-grid-npm-package.md)). ### Step 2b: Add the SendGrid npm Package Use the [Package Manager](https://dev.wix.com/docs/develop-websites/articles/coding-with-velo/packages/about-npm-packages.md) to add the SendGrid npm package to your site: 1. In the Code sidebar, click the **Code Files** ![](https://d2x3xhvgiqkx42.cloudfront.net/12345678-1234-1234-1234-1234567890ab/0ca9e8ba-16ed-4cd8-a1e1-58d01c4420f7/2021/10/13/78515cd5-9279-4fb1-a136-6a07589a5aaa/5a63551d-467b-4d54-b039-5588426d4ff7.png)  tab.  2. In the Packages section, hover over **npm**, click the plus icon ![](https://d2x3xhvgiqkx42.cloudfront.net/12345678-1234-1234-1234-1234567890ab/0ca9e8ba-16ed-4cd8-a1e1-58d01c4420f7/2021/10/13/04083fa4-3262-4606-98d1-cbc359bf8585/1a26226e-c281-42d2-8a60-88e44fe40c61.png)  and select **Install package from npm**. ![](https://d2x3xhvgiqkx42.cloudfront.net/12345678-1234-1234-1234-1234567890ab/0ca9e8ba-16ed-4cd8-a1e1-58d01c4420f7/2021/10/13/dce8e3fb-026d-4605-b51c-c8b552f0e50d/6d6bc9e2-6b26-4d8d-a3b4-f3283469ec0d.png) The Package Manager opens. 3. In the search bar, enter '**sendgrid**'. 4. 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 Code sidebar. ![](https://d2x3xhvgiqkx42.cloudfront.net/12345678-1234-1234-1234-1234567890ab/0ca9e8ba-16ed-4cd8-a1e1-58d01c4420f7/2021/10/13/411a1411-8247-4e53-86c0-6f21bdbe4db6/24bfd60a-d671-42b5-b611-65579ab2a1e2.png) Now you can import the package and use its functionality in your code. ### Step 2c: Add Page Elements To create a custom form, add the following elements to your **Home** page: * 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.web.js Web Module Since backend code is more secure, we wrote code to implement the following functionality in a [backend web module](https://dev.wix.com/docs/develop-websites/articles/coding-with-velo/backend-code/web-modules/call-backend-code-from-the-frontend.md):  1. Extract the SendGrid API key from the Secrets Manager. 2. Set the API key in SendGrid. 3. Send an email using a SendGrid npm package function. >**Note** > To see all the code for this example in a single block, [scroll down](https://dev.wix.com/docs/develop-websites/articles/code-tutorials/wix-editor-elements/send-emails-using-the-send-grid-npm-package.md) to the end of the tutorial. ### Step 3a: Add a Web Module [Web modules](https://dev.wix.com/docs/develop-websites/articles/coding-with-velo/backend-code/web-modules/call-backend-code-from-the-frontend.md) are exclusive to Velo. In a web module you can write functions that run in the backend and are easily called in your frontend code. To add a web module: 1. In the Code sidebar, select the **Code Files** ![](https://d2x3xhvgiqkx42.cloudfront.net/12345678-1234-1234-1234-1234567890ab/0ca9e8ba-16ed-4cd8-a1e1-58d01c4420f7/2021/10/21/f71f916a-a0b5-4718-bacd-4fa395f0f77d/c0ef9144-9590-4f94-9c03-4392ecd5923f.png)  tab. 2. In the Backend section, click **Add web module**. ![](https://d2x3xhvgiqkx42.cloudfront.net/12345678-1234-1234-1234-1234567890ab/0ca9e8ba-16ed-4cd8-a1e1-58d01c4420f7/2021/10/21/03237b75-04f7-4941-85a3-75f37225092c/ced5cce5-83d6-42ca-9c55-0edec8d5f754.png) 3. Name the file **sendEmail.web.js**. The file will open in the [code editor](https://dev.wix.com/docs/develop-websites/articles/workspace-tools/velo-workspace/code-editor-ide/working-in-the-code-editor.md). Place the code below in the file. ### Step 3b: Import Modules Start by importing the modules you'll need: ```javascript import { Permissions, webMethod } from 'wix-web-module'; import sgMail from "@sendgrid/mail"; import wixSecretsBackend from 'wix-secrets-backend'; ``` #### Understanding the Code **Line 1**: Import the `Permissions` enum and `webMethod` function from `wix-web-module`. **Line 2**: Import the `sgMail` module containing the functions you need from the npm package that we added to our site. **Line 3**: 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. ```javascript export const sendEmail = webMethod(Permissions.Anyone, async (recipient, subject, body) => { const sendGridSecret = JSON.parse(await wixSecretsBackend.getSecret('sendGridSecret')); const key = sendGridSecret.key; const senderEmail = sendGridSecret.senderEmail; sgMail.setApiKey(key); // Function continues below ``` #### 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. ```javascript // Function continued from above const msg = { from: senderEmail, to: recipient, subject: subject, text: body }; try { return await sgMail.send(msg); } catch (error) { console.error('Error sending the email: ' + error.message); return false; } }); ``` #### 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 >**Note** > The frontend code for this tutorial is based on the setup for this example site, a custom form exposed to site visitors. If you decide to set up your site differently, you'll need to adapt the frontend code accordingly. In our page code on the frontend of our site, we do the following: 1. Get email information such as the recipient's email address and email text from site visitors via the custom form fields. 2. Validate the form fields. 3. Use the `sendEmail()` function imported from the backend with the form field values to send an email. 4. Show a success or error message. ### Step 4a: Setup First we import the function we need from the backend and set a global constant. ```javascript import { sendEmail } from 'backend/sendEmail.web'; const 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. ```javascript function checkFormFields() { return $w('#toEmail').validity.valid && $w('#subject').validity.valid && $w('#emailContent').validity.valid; } ``` #### 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. ```javascript function clearFields() { $w('#toEmail').value = ''; $w('#subject').value = ''; $w('#emailContent').value = ''; $w('#toEmail').resetValidityIndication(); $w('#subject').resetValidityIndication(); $w('#emailContent').resetValidityIndication(); } ``` #### 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. ```javascript function displayMessage(message) { $w('#messageText').text = message; $w('#messageText').show(); $w('#messageText').hide('fade', { delay: 5000 }); } ``` #### 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 When a site visitor clicks the **Send** button, we do the following: 1. Check whether all form field values are valid. 2. 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. 3. If the email transmission request is successful, clear the form fields and display a success message. If the request fails, show an error message. ```javascript $w.onReady(function () { $w('#sendButton').onClick(async () => { const passedValidations = checkFormFields(); if (passedValidations) { const emailResult = await sendEmail( $w('#toEmail').value, $w('#subject').value, $w('#emailContent').value); if (emailResult[0].statusCode === SUCCESS_CODE) { clearFields(); displayMessage('Email was sent'); } else { displayMessage('Error sending email, please verify your SendGrid account details.'); } } else { displayMessage('Validation error, please review your input fields.'); } }) }); ``` #### 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 Check out the SendGrid npm Integration [example site](https://www.wix.com/velo-examples/sendgrid-npm) or open a copy of the [site's editor](https://editor.wix.com/html/editor/web/renderer/new?siteId=5494404c-1163-4c51-8bc2-bf8466a23e34&metaSiteId=1e3b3a34-4b1e-416c-abb9-334db84d0261&autoDevMode=true) and play around with the code. Note that if you want to work with a copy of the site, you'll need to create your own account with SendGrid and save the API key in the [Secrets Manager](https://dev.wix.com/docs/develop-websites/articles/code-tutorials/wix-editor-elements/send-emails-using-the-send-grid-npm-package.md).  You can also watch a [video](https://www.youtube.com/watch?v=jNI2MAno1_o), which describes the steps in this tutorial. ## Example Code Here is the complete code for this example: #### Backend Code in sendEmail.web File ```javascript import { Permissions, webMethod } from 'wix-web-module'; import sgMail from '@sendgrid/mail'; import wixSecretsBackend from 'wix-secrets-backend'; export const sendEmail = webMethod(Permissions.Anyone, async (recipient, subject, body) => { const sendGridSecret = JSON.parse(await wixSecretsBackend.getSecret('sendGridSecret')); const key = sendGridSecret.key; const senderEmail = sendGridSecret.senderEmail; sgMail.setApiKey(key); const msg = { from: senderEmail, to: recipient, subject: subject, text: body }; try { return await sgMail.send(msg); } catch (error) { console.error('Error sending the email: ' + error.message); return false; } }); ``` #### Frontend Page Code ```javascript import { sendEmail } from 'backend/sendEmail.web'; const SUCCESS_CODE = 202; $w.onReady(function () { $w('#sendButton').onClick(async () => { const passedValidations = checkFormFields(); if (passedValidations) { const emailResult = await sendEmail($w('#toEmail').value, $w('#subject').value, $w('#emailContent').value); if (emailResult[0].statusCode === SUCCESS_CODE) { clearFields(); displayMessage('Email was sent.'); } else { displayMessage('Error sending email, please verify your SendGrid account details.'); } } else { displayMessage('Validation error, please review your input fields.'); } }) }); function checkFormFields() { return $w('#toEmail').validity.valid && $w('#subject').validity.valid && $w('#emailContent').validity.valid; } function clearFields() { $w('#toEmail').value = ''; $w('#subject').value = ''; $w('#emailContent').value = ''; $w('#toEmail').resetValidityIndication(); $w('#subject').resetValidityIndication(); $w('#emailContent').resetValidityIndication(); } function displayMessage(message) { $w('#messageText').text = message; $w('#messageText').show(); $w('#messageText').hide('fade', { delay: 5000 }); } ```