How To Use Sendgrid In Html

SendGrid is a robust platform that operates in the cloud and is utilized for sending both transactional and promotional emails. It offers dependable delivery, the capability to scale, and immediate analytical insights, all supported by versatile APIs that simplify customized integration. This blog post will outline the steps for utilizing SendGrid in HTML.

Prerequisites

To follow along, make sure you have an active SendGrid account. If you don’t have one, you can create it on the SendGrid website.

Generating SendGrid API Key

The first step is to generate a SendGrid API key. This key is used to authenticate your application or website to SendGrid’s service.

After logging in, navigate to the ‘Settings’ section of your SendGrid dashboard, and click on ‘API Keys’. Click on ‘Create API Key’, set your permissions, and then click ‘Create & View’. You will now see your new API key. Store this key securely, as you won’t be able to access it again.

Integrating SendGrid into Your HTML page

Next, we will explain how to integrate SendGrid into your HTML page. Since HTML alone cannot send emails, we will use JavaScript (Node.js) as our server-side language to send emails using SendGrid.

Firstly, add the following form to your HTML page. This form allows the user to enter the recipient’s email, subject, and message.

<br>
    &lt;form id="emailForm"&gt;<br>
    &#160;&#160;&#160;&#160;&lt;input type="text" id="email" placeholder="Recipient's email"&gt;<br>
    &#160;&#160;&#160;&#160;&lt;input type="text" id="subject" placeholder="Subject"&gt;<br>
    &#160;&#160;&#160;&#160;&lt;textarea id="message" placeholder="Message"&gt;&lt;/textarea&gt;<br>
    &#160;&#160;&#160;&#160;&lt;button type="submit"&gt;Send Email&lt;/button&gt;<br>
    &lt;/form&gt;<br>
    

Next, we’ll need to add the following JavaScript code to send the email when the form is submitted.

<br>
    const sgMail = require('@sendgrid/mail');<br>
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);<br>
    const sendEmail = (email, subject, message) =&gt; {<br>
    &#160;&#160;&#160;&#160;const msg = {<br>
    &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;to: email,<br>
    &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;from: '[email protected]',<br>
    &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;subject: subject,<br>
    &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;text: message,<br>
    &#160;&#160;&#160;&#160;};<br>
    &#160;&#160;&#160;&#160;sgMail.send(msg);<br>
    }<br>
    

Replace ‘[email protected]’ with your own email or a dummy email. This email address will be shown as the sender’s email.

Also, replace ‘process.env.SENDGRID_API_KEY’ with your own SendGrid API key.

That’s it! Now your HTML page is integrated with SendGrid, and you can send emails with it! Happy email sending!