Advanced Cloud Code

Using Sendgrid to Send emails

Introduction

This section explains how you can integrate SendGrid with a Cloud Code function. After completing this guide with step-by-step instructions, you will be ready to use your function in your App and call it at your iOS or Android App.

Prerequisites

To complete this tutorial, you will need:

Let’s get started!

We will write a function using SendGrid that you will be able to work with a lot from possibilities as Delivering messages to our customers and configuring parameters to use the SendGrid v3 REST API.

To learn how to create or access an Account in SendGrid, check the links given below:

Create a new account - Log in to your account

Step 1 - Create a SendGrid API Key

The most important step before start to code is create the correct keys to setup your enviroment. After access your account, locate in the Settings drop-down menu, the API Keys option as in the picture below:

Locate the Settings

After that, at the top right locate and choose a identification to the API Key Name, like as shown below:

Generating the key

As you can see at the image above, it’s necessary to select one option to allow the Full Access to the API Key.

After click on the Create & View to proceed with creating of the key, you will be able to see the screen below:

Copy the Key generated

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

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 sendgridEmail 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 parameters. The code is as follows:

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Parse.Cloud.define("sendgridEmail", 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!');
    }
  });

});

Hint: Remeber to change the fields from and reply_to to your personal informations.

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

Step 3 - Call Cloud Code function

In this current step, we can work with two possibilities to call our function, they’re: Android and iOS (Swift and Objective-C).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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("sendgridEmail", 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
        }
    }
});
1
2
3
4
5
6
7
8
9
10
11
12
PFCloud.callFunctionInBackground("sendgridEmail", 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
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
[PFCloud callFunctionInBackground:@"sendgridEmail"
	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
		}
	}
];

Step 4 - It’s done!

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.

In case you need any help or a function/link doesn’t work, please contact our team via chat!