> 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: Tutorial | Send Emails with the SendGrid npm Package ## Article: Tutorial | Send Emails with the SendGrid npm Package ## Article Link: https://dev.wix.com/docs/develop-websites-sdk/get-started/tutorials/members-contacts/tutorial-send-emails-with-the-send-grid-npm-package.md ## Article Content: # Tutorial | Send Emails with the SendGrid npm Package In this tutorial, you'll learn how to set up a complete email system that allows site visitors to send emails through a custom form on your Wix site. The solution uses SendGrid's API to handle email delivery while maintaining security best practices by storing sensitive API keys in Wix's Secrets Manager. SendGrid is a cloud-based email delivery platform that provides reliable email infrastructure for businesses and developers. By integrating SendGrid with your Wix site, you can send emails such as contact form submissions, order confirmations, password resets, or custom notifications to your users. This approach gives you more control over email delivery, better tracking capabilities, and higher deliverability rates compared to basic email services. 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](#step-1--create-a-sendgrid-account). 1. [Set up your site](#step-2--set-up-the-site). 1. [Write the backend code](#step-3--write-backend-code). 1. [Write the frontend code](#step-4--write-frontend-code). > The code in this article was written using the following module versions: > > - @wix/secrets (v1.0.53) > - @wix/web-methods (v.1.0.11) > > Learn how to install npm packages [in the editor](https://dev.wix.com/docs/develop-websites-sdk/code-your-site/developer-environments/packages/npm/work-with-npm-packages-in-the-editor.md) or [using the CLI](https://dev.wix.com/docs/develop-websites-sdk/code-your-site/developer-environments/packages/npm/work-with-npm-packages-with-the-cli.md). ## Step 1 | Create a SendGrid account 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, [create an API key](https://www.twilio.com/docs/sendgrid/ui/account-and-settings/api-keys#creating-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 In this step, you'll configure your Wix site by securely storing your SendGrid credentials and installing the required npm package. 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-sdk/code-your-site/developer-environments/secrets/about-the-secrets-manager.md): 1. Navigate to **Developer Tools** in the Code sidebar. 1. Under the **Security** section, select **Secrets Manager**. 1. In the top right, click **Add Secret**. 1. Set the **Secret Name** to `sendGridSecret`. 1. Store both your SendGrid API key and the verified email address associated with your SendGrid account in the secret value. Your secret value will look like this: ```json { "key": "AB.CdPEfg1HIJk-LMnoPq2R3s.T4uVwxyZAbcd567eF8fghIjKL9mN", "senderEmail": "janedoe@example.com" } ``` 1. Click **Save**. 1. Go back to the site editor and install the [npm package](https://dev.wix.com/docs/develop-websites-sdk/code-your-site/developer-environments/packages/npm/work-with-npm-packages-in-the-editor.md). ## Step 3 | Create a custom form On your **Home** page, create a custom form and add the following elements: - Input elements for the recipient's email and subject line. Give elements the IDs of `#toEmail` and `#subject`. - Text box for the email body text. Give the element the ID of `#emailContent`. - Submit button for sending the email. Give the element the ID of `#sendButton`. - Text element for displaying success and error messages. Give the element the ID of `#messageText`. ## Step 4 | Add backend code In this step, you'll securely retrieve your SendGrid credentials and handle the email sending process using SendGrid's API. 1. Add a [web module](https://dev.wix.com/docs/develop-websites-sdk/code-your-site/build-a-custom-backend/web-modules/about-web-modules.md) to your site code and call it `sendEmail.web.js`. 1. Import the modules you'll need: ```javascript import { Permissions, webMethod } from "@wix/web-methods"; import sgMail from "@sendgrid/mail"; import { secrets } from "@wix/secrets"; ``` 1. In the `sendEmail` function, get the SendGrid API key and sender email address that you saved in the Secrets Manager, and set the API key to enable usage of the SendGrid service. For this, use the [Secrets API](https://dev.wix.com/docs/sdk/backend-modules/secrets/introduction.md): ```javascript export const sendEmail = webMethod(Permissions.Anyone, async (recipient, subject, body) => { const sendGridSecret = JSON.parse((await secrets.getSecretValue('sendGridSecret')).value); const key = sendGridSecret.key; const senderEmail = sendGridSecret.senderEmail; sgMail.setApiKey(key); // Function continues below ``` 1. Set the data for the email to be sent, such as the recipient'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 by using input elements. Call the `send()` function to send the email. ```javascript // Function continued from above const msg = { from: senderEmail, to: recipient, subject: subject, text: body }; try { const result = await sgMail.send(msg); return { success: true, result: result }; } catch (error) { console.error('Error sending the email: ' + error.message); return { success: false, error: error.message }; } }); ``` ## Step 5 | Add frontend code In this step, you'll handle user interactions with the email form, validate input fields, and communicate with the backend function to send emails. 1. Open the page code file and import the function from the backend: ```javascript import { sendEmail } from "backend/sendEmail.web"; ``` 1. Add 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 ); } ``` 1. Add the `clearFields()` function to reset the form fields following a successful email transmission. The `resetValidityIndication()` function resets 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. ```javascript function clearFields() { $w("#toEmail").value = ""; $w("#subject").value = ""; $w("#emailContent").value = ""; $w("#toEmail").resetValidityIndication(); $w("#subject").resetValidityIndication(); $w("#emailContent").resetValidityIndication(); } ``` 1. Add the `displayMessage()` 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 }); } ``` 1. When a site visitor clicks the **Send** button, 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.success) { clearFields(); displayMessage("Email was sent"); } else { displayMessage("Error sending email: " + emailResult.error); } } else { displayMessage("Validation error, please review your input fields."); } }); }); ``` ## Example code Here is the complete code for this example: ### Backend code file ```javascript import { Permissions, webMethod } from "@wix/web-methods"; import sgMail from "@sendgrid/mail"; import { secrets } from "@wix/secrets"; export const sendEmail = webMethod( Permissions.Anyone, async (recipient, subject, body) => { const sendGridSecret = JSON.parse( (await secrets.getSecretValue("sendGridSecret")).value ); const key = sendGridSecret.key; const senderEmail = sendGridSecret.senderEmail; sgMail.setApiKey(key); const msg = { from: senderEmail, to: recipient, subject: subject, text: body, }; try { const result = await sgMail.send(msg); return { success: true, result: result }; } catch (error) { console.error("Error sending the email: " + error.message); return { success: false, error: error.message }; } } ); ``` ### Frontend code file ```javascript import { sendEmail } from "backend/sendEmail.web"; $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.success) { clearFields(); displayMessage("Email was sent."); } else { displayMessage("Error sending email: " + emailResult.error); } } 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 }); } ```