Cloud Code Functions

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.

Step 2.1 - Install module from Sendgrid

Create a file called package.json, and inside this file, you need to install the Twilio module, like:

1
2
3
4
5
{ 
	"dependencies": {
		"@sendgrid/mail": "*"
	}
}

Step 2.2 - Implement Cloud Code

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
Parse.Cloud.define("sendgridEmail", (request, response) => {
    const sgMail = require('@sendgrid/mail');

    // Import SendGrid module and call with your SendGrid API Key
    sgMail.setApiKey("your SendGrid API key here");
    
    const msg = {
        to: request.params.toEmail,
        replyTo: '[email protected]',
        from: '[email protected]',
         subject: request.params.subject,
        text: request.params.body
    };
    
    sgMail.send(msg).then(() => {
       response.success("The message was sent!");
    })
    .catch(error => {    
        //Log friendly error
        response.error(error.toString());
    });
});

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Parse.Cloud.define("sendgridEmail", async(request) => {
    const sgMail = require('@sendgrid/mail');

    // Import SendGrid module and call with your SendGrid API Key
    sgMail.setApiKey("your SendGrid API key here");
    
    const msg = {
        to: request.params.toEmail,
        replyTo: '[email protected]',
        from: '[email protected]',
         subject: request.params.subject,
        text: request.params.body
    };
    
    return await sgMail.send(msg);
});

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!