---
title: SendGrid API: 코드와 통합하여 이메일 전송 자동화하기
slug: docs-kr/sendgrid-api
description: 이 가이드는 SendGrid API를 사용하여 클라우드 코드에서 이메일 전송을 자동화하는 방법을 개발자에게 안내합니다.
createdAt: 2024-02-28T14:32:00.972Z
---

# Sendgrid 이메일 API 사용하기

## 소개

이 섹션에서는 SendGrid를 Cloud Code 함수와 통합하는 방법을 설명합니다. 단계별 지침을 따라 이 가이드를 완료하면, 앱에서 함수를 사용하고 iOS 또는 Android 앱에서 호출할 준비가 됩니다.

## 전제 조건

:::hint{type="info"}
이 튜토리얼을 완료하려면 다음이 필요합니다:




- Back4App에서 생성된 앱.
- &#x20;[새 앱 만들기 튜토리얼](https://www.back4app.com/docs/get-started/new-parse-app)을 따라 Back4App에서 앱을 만드는 방법을 배우세요.
- 프로젝트에 구성된 Back4App 명령줄.
- &#x20;[클라우드 코드 설정 튜토리얼](https://www.back4app.com/docs/local-development/parse-cli)을 따라 프로젝트에 대한 클라우드 코드를 설정하는 방법을 배우세요.
- &#x20;[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"}
위 이미지에서 볼 수 있듯이, *API 키에 대한 전체 액세스&#x20;*&#xC744; 허용하기 위해 하나의 옵션을 선택해야 합니다.
:::

키 생성을 진행하기 위해 <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">`from`</font> 및 <font color="#2166ae">`reply_to`</font> 당신의 개인 정보로.
:::

그런 다음 앱에서 Cloud Code 함수를 호출하는 것이 필요합니다.

## 3 - Cloud Code 함수 호출

현재 단계에서는 두 가지 가능성을 가지고 함수를 호출할 수 있습니다. 그것은: Android와 iOS(스위프트 및 오브젝티브-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를 사용하도록 허용하기 전에 어떤 형태의 인증을 사용하는 것이 좋습니다.

도움이 필요하시거나 함수/링크가 작동하지 않는 경우, 채팅을 통해 저희 팀에 문의해 주세요!
