Using SendGrid to send email

It is nice to note that SendGrid’s API is fully compatible with Back4App’s Parse Server, so that this tutorial implements a way to use SendGrid’s API. Just in case you are unfamiliar with Parse’s API, check out the guides below – which will help you with this tutorial.

Cloud Code with Swift Apps

Cloud Code for Android

Now, we need to create a SendGrid API Key.

Step 1 – Create a SendGrid API Key

Before coding the function, we need to setup the SendGrid account to be able to send emails. Create an account at SendGrid and locate in the Settings drop-down menu, the API Keys option as in the picture below:

sendgrid_api_keys

Now, locate and find the Create API Key drop-down and click on General API Key:

sendgrid_create_api_key

Add a name to your API Key, as shown below:

sendgrid_name

Scroll down and locate the Mail Send option and click on the full access radio button, as shown:

sendgrid_mailsend

Hit the Save button and your SendGrid API Key will be shown, just like this one:

sendgrid_tampered

Be careful to write it down, as there is no way to retrieve it. Click on the text to copy it.

Now, to the next step.

Step 2 – Add a function to the Cloud Code

The main strategy to this way of using SendGrid’s API is to create a function on the Cloud Code named “sendEmail” and call it from the App. You should note that every email field has to be send by the App – from the subject to the content – as a parametre. The code is as follows:

Parse.Cloud.define("sendEmail", function(request, response) {

  // Import SendGrid module and call with your SendGrid API Key
  var sg = require('sendgrid')('your SendGrid API key here');

  // Create the SendGrid Request
  var reqSG = sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: {
      personalizations: [
        {
          to: [
            {
              // This field is the "to" in the email
              email: request.params.toEmail,
            },
          ],
          // This field is the "subject" in the email
          subject: request.params.subject,
        },
      ],
      // This field contains the "from" information
      from: {
        email: [email protected]',
        name: 'Your Name',
      },
      // This contains info about the "reply-to"
      // Note that the "reply-to" may be different than the "from"
      reply_to: {
        email: [email protected]',
        name: 'Your Name',
      },
      content: [
        {
          // You may want to leave this in text/plain,
          // Although some email providers may accept text/html
          type: 'text/plain',
          // This field is the body of the email
          value: request.params.body,
        },
      ],
    },
  });

  // Make a SendGrid API Call
  sg.API(reqSG, function(SGerror, SGresponse) {
    // Testing if some error occurred
    if (SGerror) {
      // Ops, something went wrong
      console.error('Error response received');
      console.error('StatusCode=' + SGresponse.statusCode);
      console.error(JSON.stringify(SGresponse.body));
      response.error('Error = ' + JSON.stringify(SGresponse.body));
    } 
    else {
      // Everything went fine
      console.log('Email sent!');
      response.success('Email sent!');
    }
  });

});

Then it is necessary to implement a call to the Cloud Code function on the app.

Step 3 – Call Cloud Code function from the App

Then you should call the function from your App. Here are some sample code to call it:

Android:

Map<String, String> params = new HashMap<>();

// Create the fields "emailAddress", "emailSubject" and "emailBody"
// As Strings and use this piece of code to add it to the request
params.put("toEmail", emailAddress);
params.put("subject", emailSubject);
params.put("body", emailBody);

ParseCloud.callFunctionInBackground("sendEmail", params, new FunctionCallback<Object>() {
    @Override
    public void done(Object response, ParseException exc) {
        if(exc == null) {
            // The function executed, but still has to check the response
        }
        else {
            // Something went wrong
        }
    }
});

iOS Objective-C:

[PFCloud callFunctionInBackground:@"sendEmail"
         withParameters:@{@"toEmail": toEmail,
                          @"subject": subject,
                          @"body": body}
         block:^(NSString *myAlertMsg, NSError *error){
               if(!error) {
                   // The function executed, but still has to check the response
               }
               else {
                   // The function returned an error
               }
          }
];

iOS Swift:

PFCloud.callFunctionInBackground(“sendEmail”, withParameters: [
    // These fields have to be defined earlier
    "toEmail": toEmail,
    "subject": subject,
    "body": body
]) { (response, error) in
    if error == nil {
        // The function executed, but still has to check the response
    } else {
        // The function returned an error
    }
}

And that’s it for the SendGrid usage. Note that you might want to use some sort of authentication before allowing anyone to use your SendGrid API to send emails.