cfoster5
cfoster5

Reputation: 1826

Trying to use SendGrid with Angular and Node

Using Angular and SendGrid, I am trying to send an email. I installed the NPM package correctly but am having issues with implementing the code. I generated an API key and stored it in the directory with

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

The Typescript is:

sgemail(){
  const sgMail = require('@sendgrid/mail'); //ERROR: Cannot find name 'require'.
  sgMail.setApiKey(process.env.SENDGRID_API_KEY); //ERROR: Cannot find name 'process'.
  const msg = {
    to: '[email protected]',
    from: '[email protected]',
    subject: 'Sending with SendGrid is Fun',
    text: 'and easy to do anywhere, even with Node.js',
    html: '<strong>and easy to do anywhere, even with Node.js</strong>',
  };
  console.log(msg);
  sgMail.send(msg);
}

I am firing this on a button click.

Sendgrid has no information on their site about importing packages like how you have to use import { Vibration } from '@ionic-native/vibration'; to use Ionic's vibration package.

Upvotes: 1

Views: 6164

Answers (1)

Sam S
Sam S

Reputation: 566

You could try sending a POST request manually using fetch to their Send Mail API. And don't forget the Authorization Headers. Below is a same untested JavaScript code snippet to try. Fill in YOUR_API_KEY and update the to email to one of your emails.

  var payload = {
    "personalizations": [
      {
        "to": [
          {
            "email": "[email protected]"
          }
        ],
        "subject": "Hello, World!"
      }
    ],
    "from": {
      "email": "[email protected]"
    },
    "content": [
      {
        "type": "text/plain",
        "value": "Hello, World!"
      }
    ]
  };
  var myHeaders = new Headers({
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY",
  });
  var data = new FormData();
  data.append( "json", JSON.stringify( payload ) );
  fetch("https://api.sendgrid.com/v3/mail/send",
  {
      method: "POST",
      headers: myHeaders,
      body: data
  })
  .then(function(res){ return res.json(); })
  .then(function(data){ console.log( JSON.stringify( data ) ) })

Upvotes: 2

Related Questions