1

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.

1 Answer 1

2

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 ) ) })
Sign up to request clarification or add additional context in comments.

1 Comment

Access to fetch at 'api.sendgrid.com/v3/mail/send' from origin 'localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'sendgrid.api-docs.io' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.