sendgrid / sendgrid-nodejs

The Official Twilio SendGrid Led, Community Driven Node.js API Library
https://sendgrid.com
MIT License
3k stars 781 forks source link

I can not send emails with Sendgrid/mail #922

Closed The-Caesar closed 4 years ago

The-Caesar commented 5 years ago

Dear,

I can not send emails :(

I get this response:

{ Error: Bad Request at Request.http [as _callback] (...\module\storemonitoring-fa\node_modules\@sendgrid\client\src\classes\client.js:124:25) at Request.self.callback (...\module\storemonitoring-fa\node_modules\@sendgrid\client\node_modules\request\request.js:185:22) at emitTwo (events.js:126:13) at Request.emit (events.js:214:7) at Request. (....\module\storemonitoring-fa\node_modules\@sendgrid\client\node_modules\request\request.js:1161:10) at emitOne (events.js:116:13) at Request.emit (events.js:211:7) at IncomingMessage. (....\module\storemonitoring-fa\node_modules\@sendgrid\client\node_modules\request\request.js:1083:12) at Object.onceWrapper (events.js:313:30) at emitNone (events.js:111:20) code: 400, message: 'Bad Request', response: { headers: { server: 'nginx', date: 'Thu, 02 May 2019 07:29:09 GMT', 'content-type': 'application/json', 'content-length': '204', connection: 'close', 'access-control-allow-origin': 'https://sendgrid.api-docs.io', 'access-control-allow-methods': 'POST', 'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl', 'access-control-max-age': '600', 'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' }, body: { errors: [Array] } } }

sendgrid-nodejs Version: "@sendgrid/mail": "^6.3.1" Node.js Version: 8.13.0

aroach commented 5 years ago

Can you post your code that is throwing this? Also, if you can inspect body: { errors: [Array] } you might have some more clues. Since it's a 400, it's on the client side, and likely how you're building up the request to the servers.

The-Caesar commented 5 years ago

here what i do to send mail i declare: 1- const sgMail = require('@sendgrid/mail'); then i configure my mail with APIKey 2- sgMail.setApiKey(config.sendGridAPIKey); then i fill my emailsData with Emails that i want to send depending on my treatment: 3- let emailsData = []; then i send my emails: 4- sgMail.send(emailsData) and for the body i'm using html as body from emailtemplate.js

const htmlTemplate = templateHelper.generateNewMatchingsHTML(matchingsStats);

generateEmailStoreData(emails, retailChainId, storeId, htmlTemplate) { return { 'from': 'xxxxxxxxxxxx@xxxx.xxx', 'to': 'emails', 'subject':[Stores-monitoring] ${retailChainId} - ${storeId}, 'html': htmlTemplate }; }

PS: it was to work but not anymore

thinkingserious commented 5 years ago

Hello @The-Caesar,

It looks like emailsData is of the wrong type. Please see this example.

With Best Regards,

Elmer

The-Caesar commented 5 years ago

emailsData is a array of emails wich is filled with hmtl template depends on my treatement, as i said before so when i want to send an email i just push my email to "emailsData" and send them all by calling "sgMail.send(emailsData)" so in other word i'm sending many emails in just one call !!

aroach commented 5 years ago

Comparing with the example code shared by Elmer, emailsData in your example should be a JavaScript Object and not an array. The to property of the JS Object can be an array.

let emailsData = { to: [], ... }

Please give that a try and let us know!

On Fri, May 3, 2019 at 4:42 PM Mansouri notifications@github.com wrote:

emailsData is a array of emails wich is filled with hmtl template depends on my treatement as i said before so when i want to send an email i just push my email to "emailsData" and send them all by calling "sgMail.send(emailsData)" so in other word i'm sending many email in just one call !!

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/sendgrid/sendgrid-nodejs/issues/922#issuecomment-489262242, or mute the thread https://github.com/notifications/unsubscribe-auth/AARP5MU6L2DABGI2I3GRTJ3PTS5WLANCNFSM4HJ4AS3Q .

izznogooood commented 5 years ago

I can verify this: (It worked a few days ago, updated to latest npm (after fail, still fails))

const sgMail = require('@sendgrid/mail');

const sendGridAPIKey = someMagic();
sgMail.setApiKey(sendGridAPIKey);

const sendWelcomeEmail = async (email, name) => {
    try {
        await sgMail.send({
            to: email,
            from: 'fancy@email.not',
            subject: 'Welcome to my site',
            text: `Welcome to the app, ${name}.`,
            html: ''
        });
    } catch (e) {
        console.log(e);
    }
};

Output:

{ ResponseError: Bad Request
    at Request.http [as _callback] (node_modules/@sendgrid/client/src/classes/client.js:124:25)
    at Request.self.callback (node_modules/request/request.js:185:22)
    at Request.emit (events.js:193:13)
    at Request.<anonymous> (node_modules/request/request.js:1161:10)
    at Request.emit (events.js:193:13)
    at IncomingMessage.<anonymous> (node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:281:20)
    at IncomingMessage.emit (events.js:198:15)
    at endReadableNT (_stream_readable.js:1139:12)
    at processTicksAndRejections (internal/process/task_queues.js:81:17)
  code: 400,
  message: 'Bad Request',
  response:
   { headers:
      { server: 'nginx',
        date: 'Wed, 08 May 2019 19:38:58 GMT',
        'content-type': 'application/json',
        'content-length': '219',
        connection: 'close',
        'access-control-allow-origin': 'https://sendgrid.api-docs.io',
        'access-control-allow-methods': 'POST',
        'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
        'access-control-max-age': '600',
        'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' },
     body: { errors: [Array] } } } // <-- Dont know how to parse this.
Full-Stack-Zach commented 5 years ago

@izznogooood, I tried this same block of code in my application. Not getting any errors but the emails are not sending at all.

izznogooood commented 5 years ago

yup, something's up...

I use it for testing so not as bad for me. But happy to help.

Full-Stack-Zach commented 5 years ago

I've been working on this for a while now and can't get SendGrid to consistently send emails any way I try in NodeJs. Currently looking at other service providers because I need email functionality to start working soon. Let me know if you figure out how to get it working. I'd love to stick with this if it works.

aroach commented 5 years ago

The code block provided never calls the sendWelcomeEmail() function, and so it never executes.

But, after fixing that, this code worked (note that I removed the empty html property:

Tested using node v8.12.0.

const sgMail = require('@sendgrid/mail');

const sendGridAPIKey = 'SG.xxx.yyy';
sgMail.setApiKey(sendGridAPIKey);

const email = 'me@gmail.com';
const name = 'Ashley Roach';

const sendWelcomeEmail = async (email, name) => {
    try {
        await sgMail.send({
            to: email,
            from: 'fancy@email.not',
            subject: 'Welcome to my site',
            text: `Welcome to the app, ${name}.`,
        });
    } catch (e) {
        console.log(e);
    }
};

sendWelcomeEmail(email, name);
thinkingserious commented 5 years ago

Hello everyone,

@izznogooood,

Please see this documentation on how to capture the error message.

@The-Caesar,

Could you either provide a full code sample or the value of the msg you pass to .send?

@Full-Stack-Zach,

Could you please provide some code that I can use to try and reproduce your issue?

FWIW, here is what works for me using @sendgrid/mail@6.4.0:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'ethomas@twilio.com',
  from: 'dx@sendgrid.com',
  subject: 'Hello world',
  text: 'Hello plain world!'
};

sgMail
  .send(msg)
  .then(() => {
    //Celebrate
    console.log('Email Sent!');
  })
  .catch(error => {

    //Log friendly error
    console.error(error.toString());

    //Extract error msg
    const {message, code, response} = error;

    //Extract response msg
    const {headers, body} = response;
  });

I hope this is helpful.

With Best Regards,

Elmer

izznogooood commented 5 years ago

@thinkingserious

Node version 10.15.2

console.log(e.response.body);

// message
{ errors:
   [ { message:
        'The content value must be a string at least one character in length.',
       field: 'content.1.value',
       help:
        'http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.content.value' } ] }

So in my case it was as simple as adding a space in my html string (or remove it)... But I dont belive I've done that before. But thank you.

@Full-Stack-Zach I assumed you'd call the function, that was my bad. Sorry about that.

The-Caesar commented 5 years ago

here an object from the array emailsData: emailsData[0].txt

thinkingserious commented 5 years ago

Hello @The-Caesar,

One think I noticed is that you don't have a text value. Can you try adding a text value? Also, what is the value of the emails variable?

Thanks!

With Best Regards,

Elmer

andrewlew1s commented 5 years ago

I got this response when entering an invalid email.

MeisterJustice commented 5 years ago

I got this response when entering an invalid email.

Thanks so much man. I spent hours on this error until this.

himanshuhx commented 4 years ago

Hello Everyone i was using wordpress to buid my portfolio which i hosted on github the contact form part is working on localhost in my system and i am getting the mail bur when i pushed the code to github it is not working and i am not getting the mail.i am using sendGrid for this .Can anyone help? Thank you

childish-sambino commented 4 years ago

@himanshuhx Please open a new issue.