Sendgrid-nodejs: Multiple emails received per each API call

Created on 22 Jun 2017  路  13Comments  路  Source: sendgrid/sendgrid-nodejs

I am trying the API v3 to send emails in Java (Android). However, for each call to send an email, I usually receive about four at a go. Is this due to something bad going on?

help wanted question

Most helpful comment

@ansmonjol +1, thanks for sharing. For some weird reason, the problem has stopped without any changes to my code :). I don't know what happened. Just keeping an eye on it for while, if everything keeps working well I will come back and close this ticket later.

All 13 comments

HI @saintjab,

Do you mind sharing our source code? It sounds like you might have a logic error.

With Best Regards,

Elmer

@thinkingserious
This is the code I am using

var helper = require('sendgrid').mail;
        var fromEmail = new helper.Email('[email protected]');
        var toEmail = new helper.Email(request.params.toEmail);
        var subject = request.params.subject;
        var content = new helper.Content('text/plain', request.params.body);
        var mail = new helper.Mail(fromEmail, subject, toEmail, content);

        var sg = require('sendgrid')(SENDGRID_KEY);
        var request = sg.emptyRequest({
            method: 'POST',
            path: '/v3/mail/send',
            body: mail.toJSON()
        });

        sg.API(request, function (error, response) {
             if (error) {
                  console.log('Error response received');
        }

        console.log('Status code: ' +response.statusCode);
        console.log('Body: ' +response.body);
        console.log('Header: ' +response.headers);
});

I am calling this as a function so the request.params are filled. Thanks

Got the same error with quite the same code @saintjab.
I receive 2 mails with the same call to sendgrid api, one with all the data I want into my mail, the second is empty, got only the "static" text in the template message

@saintjab, @ansmonjol,

Could you please provide the output to mail.toJSON()?

Can you verify that your code is only calling sg.API once?

Thanks!

I've put a log in the sg.API like the following:

      sg.API(request, (error, response) => {
        console.log('im here');
        if (error) {
          console.log('Error response received');
          console.log(response.statusCode);
          console.log(response.body);
          console.log(response.headers);
        }
      });

And I can see im here only once

--

Here is the Mail.toJSON():

{ from: { email: '[email protected]', name: 'MyCompany' },
  personalizations: 
   [ Personalization {
       tos: [Object],
       ccs: undefined,
       bccs: undefined,
       subject: undefined,
       headers: undefined,
       substitutions: undefined,
       custom_args: undefined,
       send_at: undefined,
       addTo: [Function],
       getTos: [Function],
       addCc: [Function],
       getCcs: [Function],
       addBcc: [Function],
       getBccs: [Function],
       setSubject: [Function],
       getSubject: [Function],
       addHeader: [Function],
       getHeaders: [Function],
       addSubstitution: [Function],
       getSubstitutions: [Function],
       addCustomArg: [Function],
       getCustomArgs: [Function],
       setSendAt: [Function],
       getSendAt: [Function],
       toJSON: [Function] },
     Personalization {
       tos: [Object],
       ccs: undefined,
       bccs: undefined,
       subject: ' ',
       headers: undefined,
       substitutions: [Object],
       custom_args: undefined,
       send_at: undefined,
       addTo: [Function],
       getTos: [Function],
       addCc: [Function],
       getCcs: [Function],
       addBcc: [Function],
       getBccs: [Function],
       setSubject: [Function],
       getSubject: [Function],
       addHeader: [Function],
       getHeaders: [Function],
       addSubstitution: [Function],
       getSubstitutions: [Function],
       addCustomArg: [Function],
       getCustomArgs: [Function],
       setSendAt: [Function],
       getSendAt: [Function],
       toJSON: [Function] } ],
  subject: ' ',
  content: [ { type: 'text/html', value: ' ' } ],
  attachments: undefined,
  template_id: 'X_myTemplateId_X',
  sections: undefined,
  headers: undefined,
  categories: undefined,
  custom_args: undefined,
  send_at: undefined,
  batch_id: undefined,
  asm: undefined,
  ip_pool_name: undefined,
  mail_settings: undefined,
  tracking_settings: undefined,
  reply_to: undefined }

--

So got 2 Personalization in the mail. Could it be the reason ?
Even if the im here only show once

Thank you

I am not able to run the code at all at the moment. I get error: _unauthorized code=141, message=unauthorized_ . I am calling this through a Parse Cloud Code so not exactly sure where the error is coming from.

@ansmonjol,

Yes, the two personalizations are the problem. We have to figure out why you are generating two of them. One common reason this happens is when you mix using the mail helper constructor with building a custom mail object. Here is an example of setting up the mail object without using the constructor. Could you please try that?

@saintjab,

That sounds like an issue with your API credentials.

Thanks!

@Thinkingserious, that is weird because I haven't changed my API credentials and even though I created a new key just to confirm that, none of the changes made any difference so I revert back to the previous key.

You're right !

I was adding a toEmail twice, one in the mail object and one in the personalization

So I removed

const mail = new helper.Mail(fromEmail, subject, toEmail, content);

and changed it by

const mail = new helper.Mail();

mail.setFrom(fromEmail);
mail.setSubject(subject);
mail.addContent(content);
const personalization = new helper.Personalization();
personalization.addTo(toEmail);

And it work perfectly fine 馃檶

Thanks

@saintjab,

The format of that error does not look like it's coming from SendGrid. We do not return a 141 code. Perhaps there is an issue with Parse or another library?

@thinkingserious , here is my mail.toJSON

M2JSONfunction () {
var json = {
from: this.getFrom(),
personalizations: this.getPersonalizations(),
subject: this.getSubject(),
content: this.getContents(),
attachments: this.getAttachments(),
template_id: this.getTemplateId(),
sections: this.getSections(),
headers: this.getHeaders(),
categories: this.getCategories(),
custom_args: this.getCustomArgs(),
send_at: this.getSendAt(),
batch_id: this.getBatchId(),
asm: this.getAsm(),
ip_pool_name: this.getIpPoolName(),
mail_settings: this.getMailSettings(),
tracking_settings: this.getTrackingSettings(),
reply_to: this.getReplyTo(),
};

return json;

}
and for some reason, I logged sg.API calls and there were many calls to it. I don't know what is happen.
@ansmonjol Do you mind sharing your code so I can verify something?
Thanks

Sure ! Here is my complete code @saintjab with a template send :

  static async sendTemplate(params) {
    if (localeConfig.DISABLED_EMAIL !== true) {
      const mail = new helper.Mail();
      const fromEmail = new helper.Email('[email protected]', 'Company Name');
      const subject = params.subject || ' ';
      const toEmail = new helper.Email(params.recipients[0].email);
      const content = new helper.Content('text/html', params.body || ' ');

      mail.setFrom(fromEmail);
      mail.setSubject(subject);
      mail.addContent(content);

      const personalization = new helper.Personalization();
      personalization.addTo(toEmail);
      personalization.setSubject(params.subject || ' ');
      const bodyParams = params.bodyParams || {};

      const keys = Object.keys(bodyParams);
      for (let k = 0; k < keys.length; k++) {
        const key = keys[k].toUpperCase();
        const value = String(bodyParams[keys[k]]);
        const substitution = new helper.Substitution(`*|${key}|*`, value);
        personalization.addSubstitution(substitution);
      }

      mail.addPersonalization(personalization);
      if (params.invoice) {
        const attachment = new helper.Attachment();
        const file = fs.readFileSync(path.join(__dirname, '../../../public/files', `${params.invoice}`));
        const base64File = new Buffer(file).toString('base64');
        attachment.setContent(base64File);
        attachment.setType('application/pdf');
        attachment.setFilename(`Company - ${params.bodyParams.date}.pdf`);
        attachment.setDisposition('attachment');
        mail.addAttachment(attachment);
      }

      mail.template_id = params.template_id;
      const sg = require('sendgrid')(parameters.API_KEY);
      const request = sg.emptyRequest({
        method: 'POST',
        path: '/v3/mail/send',
        body: mail.toJSON()
      });

      sg.API(request, (error, response) => {
        if (error) {
          console.log('Error response received');
          console.log(response.statusCode);
          console.log(response.body);
          console.log(response.headers);
        }
      });
    }
    return true;
  }

It's not really commented so tell me if you have some questions.

1st we build the email part (from, subject, content)
then add the personalizations stuff (to, subject (again), vars for the templates)
then if it's an invoice send, we add the file
build the request and send

@ansmonjol +1, thanks for sharing. For some weird reason, the problem has stopped without any changes to my code :). I don't know what happened. Just keeping an eye on it for while, if everything keeps working well I will come back and close this ticket later.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Loriot-n picture Loriot-n  路  4Comments

thinkingserious picture thinkingserious  路  4Comments

nicoasp picture nicoasp  路  3Comments

zvone187 picture zvone187  路  4Comments

polkhovsky picture polkhovsky  路  3Comments