---
title: 使用SendGrid邮件API集成Cloud Code函数指南
slug: docs-ch/sendgridapicloud-code
description: 学习如何通过SendGrid邮件API与Cloud Code函数集成，发送iOS及Android应用程序邮件。
createdAt: 2024-02-28T14:32:00.972Z
---

# 使用 Sendgrid 邮件 API

## 介绍

本节解释了如何将 SendGrid 与 Cloud Code 函数集成。在完成本指南的逐步说明后，您将能够在您的应用程序中使用该函数，并在您的 iOS 或 Android 应用程序中调用它。

## 先决条件

:::hint{type="info"}
要完成本教程，您需要：




- 在 Back4App 创建的应用程序。
- 请遵循 [创建新应用程序教程](https://www.back4app.com/docs/get-started/new-parse-app) 以了解如何在 Back4App 上创建应用程序。
- 与项目配置的 Back4App 命令行工具。
- 请遵循 [设置 Cloud Code 教程](https://www.back4app.com/docs/local-development/parse-cli) 以了解如何为项目设置云代码。
- 在 [Twilio](https://login.twilio.com/u/signup?state=hKFo2SBSTHoyUXZ1NnUzTjZaMHk2Q3EtaXV5LUtnUlhaMzdtN6Fur3VuaXZlcnNhbC1sb2dpbqN0aWTZIE9JTzFKSU9LaVMzTV9fYVo0VDM0a2pnSEpZM09SYUo4o2NpZNkgTW05M1lTTDVSclpmNzdobUlKZFI3QktZYjZPOXV1cks) 创建的帐户。
:::

## 让我们开始吧！

我们将使用 SendGrid 编写一个函数，您将能够利用许多可能性，例如向我们的客户发送消息和配置参数以使用 SendGrid v3 REST API。

要了解如何在 SendGrid 中创建或访问帐户，请查看以下链接：

[创建新帐户](https://signup.sendgrid.com/) - [登录到您的帐户](https://app.sendgrid.com/login)

## 1 - 创建 SendGrid API 密钥

在开始编码之前，最重要的一步是创建正确的密钥以设置您的环境。在访问您的帐户后，在设置下拉菜单中找到 <font color="#2166ae">`API 密钥`</font> 选项，如下图所示:

::Image[]{src="https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/S5lS0LacIcaC-xBz3Krya_image.png" size="30" width="162" height="207" position="center" showCaption="false"}

之后，在右上角找到并选择一个标识以为<font color="#2166ae">`API 密钥名称`</font>, 如下所示:

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/LqdAOYbNuSKMivIdMPwD8_image.png)

:::hint{type="info"}
正如您在上面的图像中所看到的，选择一个选项以允许 *完全访问&#x20;*&#x41;PI 密钥是必要的。
:::

点击 <font color="#2166ae">`创建并查看`</font> 以继续创建密钥后，您将能够看到如下屏幕:

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/-saVIVCBs8al5vGK3c4In_image.png)

:::hint{type="warning"}
**提示**: 请小心记录，因为无法找回。点击文本以复制它。
:::

## 2 - 向云代码添加一个函数

使用 SendGrid API 的主要策略是创建一个名为 <font color="#2166ae">`sendgridEmail`</font> 的云代码函数，并从应用程序中调用它。

### 2.1 - 从 Sendgrid 安装模块

创建一个名为 <font color="#2166ae">`package.json`</font>, 在这个文件中，您需要安装 Twilio 模块，如下所示：

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

### 2.2 - 实现云代码

您应该注意，每个电子邮件字段都必须由应用程序发送——从主题到内容——作为参数。代码如下：

:::CodeblockTabs
Parse Server 3.X

```javascript
1   Parse.Cloud.define("sendgridEmail", async(request) => {
2       const sgMail = require('@sendgrid/mail');
3
4       // Import SendGrid module and call with your SendGrid API Key
5       sgMail.setApiKey("your SendGrid API key here");
6    
7       const msg = {
8           to: request.params.toEmail,
9           replyTo: 'info@youremail.com',
10          from: 'info@youremail.com',
11           subject: request.params.subject,
12          text: request.params.body
13      };
14
15      try{
16        await sgMail.send(msg);
17        return 'OK'
18      } catch (e){
19        return `Error: ${e.message}`
20      }
21     
22  });
```

Parse Server 2.X

```javascript
1   Parse.Cloud.define("sendgridEmail", (request, response) => {
2       const sgMail = require('@sendgrid/mail');
3
4       // Import SendGrid module and call with your SendGrid API Key
5       sgMail.setApiKey("your SendGrid API key here");
6    
7       const msg = {
8           to: request.params.toEmail,
9           replyTo: 'info@youremail.com',
10          from: 'info@youremail.com',
11           subject: request.params.subject,
12          text: request.params.body
13      };
14    
15      sgMail.send(msg).then(() => {
16         response.success("The message was sent!");
17      })
18      .catch(error => {    
19          //Log friendly error
20          response.error(error.toString());
21      });
22  });
```
:::

:::hint{type="warning"}
**提示**: 请记得更改字段 <font color="#2166ae">`从`</font> 和 <font color="#2166ae">`reply_to`</font> 到您的个人信息。
:::

然后有必要在应用程序中实现对云代码函数的调用。

## 3 - 调用云代码函数

在当前步骤中，我们可以使用两种可能性来调用我们的函数，它们是：Android 和 iOS（Swift 和 Objective-C）。

:::CodeblockTabs
Android

```java
1   Map<String, String> params = new HashMap<>();
2
3   // Create the fields "emailAddress", "emailSubject" and "emailBody"
4   // As Strings and use this piece of code to add it to the request
5   params.put("toEmail", emailAddress);
6   params.put("subject", emailSubject);
7   params.put("body", emailBody);
8
9   ParseCloud.callFunctionInBackground("sendgridEmail", params, new FunctionCallback<Object>() {
10      @Override
11      public void done(Object response, ParseException exc) {
12          if(exc == null) {
13              // The function executed, but still has to check the response
14          }
15          else {
16              // Something went wrong
17          }
18      }
19  });
```

iOS(Swift)

```swift
1   PFCloud.callFunctionInBackground("sendgridEmail", withParameters: [
2       // These fields have to be defined earlier
3       "toEmail": toEmail,
4       "subject": subject,
5       "body": body
6   ]) { (response, error) in
7       if error == nil {
8           // The function executed, but still has to check the response
9       } else {
10          // The function returned an error
11      }
12  }
```

iOS(Objective-C)

```objective-c
1   [PFCloud callFunctionInBackground:@"sendgridEmail"
2	   withParameters:@{@"toEmail": toEmail,
3	             	    @"subject": subject,
4	              	    @"body": body}
5	   block:^(NSString *myAlertMsg, NSError *error){
6		   if(!error) {
7		      // The function executed, but still has to check the response
8		   }
9		   else {
10		     // The function returned an error
11		  }
12	  }
13  ];
```
:::

## 4 - 完成！

这就是 SendGrid 的使用。请注意，您可能希望在允许任何人使用您的 SendGrid API 发送电子邮件之前使用某种身份验证。

如果您需要任何帮助或某个功能/链接无法正常工作，请通过聊天与我们的团队联系！
