javascriptnode.jsemailsendgridsendgrid-api-v3

Send Sendgrid Email Without Subject


Is it possible to send an email through Sendgrid without a subject? I tried leaving the subject field blank, but I get an error message that says

TypeError: Cannot read property 'map' of undefined

Here is my code...

        var helper = require('sendgrid').mail;
        var fromEmail = new helper.Email("myemail@email.com");
        var toEmail = new helper.Email("sendEmail@email.com");

        //I set the subject to null

        var subject = null;

        var content = new helper.Content('text/html', "my message");
        var mail = new helper.Mail(fromEmail, subject, toEmail, content);

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

        sg.API(request, function (error, response) {

        });

I tried setting the subject to null and ""; but both returned error messages.

Any Ideas?


Solution

  • You can't send an email via the API with an empty subject. See the Docs here: https://sendgrid.com/docs/API_Reference/api_v3.html

    If you scroll down to the subject parameter, you'll see that it says:

    The global, or “message level”, subject of your email. This may be overridden by personalizations[x].subject. minLength 1

    And it also says that it's required. If you look at the subject param of a personalization which can overwrite the email's main subject, it points to this SO answer about the subject limits: What is the email subject length limit?

    So basically the library is written in such a way that it assumes a subject is present on that map and it will error.

    To test it I did a quick curl like this:

    curl -X POST \
      https://api.sendgrid.com/v3/mail/send \
      -H 'authorization: Bearer MYAPIKEY' \
      -H 'cache-control: no-cache' \
      -H 'content-type: application/json' \
      -d '{
      "personalizations": [
        {
          "to": [
            {
              "email": "testemail@test.com"
            }
          ],
        }
      ],
      "from": {
        "email": "testemail@test.com"
      },
      "content": [
        {
          "type": "text/plain",
          "value": "Hello, World!"
        }
      ]
    }
    

    And got this response:

    {
        "errors": [
            {
                "message": "The subject is required. You can get around this requirement if you use a template with a subject defined or if every personalization has a subject defined.",
                "field": "subject",
                "help": "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.subject"
            }
        ]
    }