

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 프로그래밍 방식으로 Amazon SES SMTP 인터페이스를 통해 이메일 전송
<a name="send-using-smtp-programmatically"></a>

Amazon SES SMTP 인터페이스를 사용하여 이메일을 전송하기 위해 SMTP 지원 프로그래밍 언어, 이메일 서버 또는 애플리케이션을 사용할 수 있습니다. 시작하기 전에 [Amazon Simple Email Service 설정](setting-up.md)의 작업을 완료해야 합니다. 또한 다음과 같은 정보가 필요합니다.
+ Amazon SES SMTP 엔드포인트와 연결하기 위한 Amazon SES SMTP 보안 인증 정보. Amazon SES SMTP 보안 인증 정보를 받으려면 [Amazon SES SMTP 자격 증명 획득](smtp-credentials.md) 섹션을 참조하세요.
**중요**  
SMTP 자격 증명은 자격 AWS 증명과 다릅니다. 자격 증명에 대한 자세한 내용은 [Amazon SES 자격 증명 유형](send-email-concepts-credentials.md) 단원을 참조하세요.
+ SMTP 엔드포인트 주소입니다. Amazon SES SMTP 엔드포인트 목록은 [Amazon SES SMTP 엔드포인트에 연결](smtp-connect.md) 섹션을 참조하세요.
+ 연결 방법에 따른 Amazon SES SMTP 인터페이스 포트 번호. 자세한 내용은 [Amazon SES SMTP 엔드포인트에 연결](smtp-connect.md) 단원을 참조하십시오.

## 코드 예제
<a name="send-email-smtp-code-examples"></a>

SMTP 지원 프로그래밍 언어를 사용하여 Amazon SES SMTP 인터페이스에 액세스할 수 있습니다. Amazon SES SMTP 호스트 이름 및 포트 번호와 사용자의 SMTP 자격 증명을 입력한 후 프로그래밍 언어의 일반 SMTP 함수를 사용하여 이메일을 전송합니다.

Amazon Elastic Compute Cloud(Amazon EC2)는 기본적으로 포트 25를 통한 이메일 트래픽을 제한합니다. Amazon EC2의 SMTP 엔드포인트를 통해 이메일을 전송할 때 시간 초과를 방지하려면 이러한 제한을 제거하도록 요청할 수 있습니다. 자세한 내용은 [ Amazon EC2 인스턴스 또는 AWS Lambda 함수에서 포트 25에 대한 제한을 제거하려면 어떻게 해야 합니까?를 참조하세요.](https://aws.amazon.com/premiumsupport/knowledge-center/ec2-port-25-throttle/) AWS 지식 센터의 .

Java 및 PHP에 대해 이 섹션의 코드 예제에서는 포트 587을 사용하여 이 문제를 방지합니다.

**참고**  
이러한 자습서에서는 수신 여부를 확인할 수 있도록 자신에게 이메일을 발송합니다. 추가적인 실험 또는 로드 테스트는 Amazon SES 메일박스 시뮬레이터를 사용하십시오. 메일박스 시뮬레이터로 전송되는 이메일은 전송 할당량이나 반송 메일 및 수신 거부 발생률에 포함되지 않습니다. 자세한 내용은 [수동으로 메일박스 시뮬레이터 사용](send-an-email-from-console.md#send-email-simulator) 단원을 참조하십시오.

**프로그래밍 언어를 선택하여 해당 언어에 대한 예제를 봅니다.**

**주의**  
Amazon SES는 정적 자격 증명 사용을 권장하지 않습니다. 소스 코드에서 하드 코딩된 자격 증명을 제거하여 보안 태세를 개선하는 방법을 알아보려면 [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) 섹션을 참조하세요. 이 자습서는 프로덕션이 아닌 환경에서 Amazon SES SMTP 인터페이스를 테스트하기 위한 목적으로만 제공됩니다.

------
#### [ Java ]

이 예제에서는 SMTP 인터페이스를 사용하여 Amazon SES 를 통해 이메일을 보내기 위해 [Eclipse IDE](http://www.eclipse.org/) 및 [JavaMail API](https://github.com/javaee/javamail/releases)를 사용합니다.

다음 절차를 수행하기 전에 [Amazon Simple Email Service 설정](setting-up.md)의 작업을 완료합니다.

**Java를 사용하여 Amazon SES SMTP 인터페이스를 통해 이메일을 전송하려면**

1. 웹 브라우저에서 [JavaMail GitHub 페이지](https://github.com/javaee/javamail/releases)로 이동합니다. **자산**에서 **javax.mail.jar**를 선택하여 최신 버전의 JavaMail을 다운로드합니다.
**중요**  
이 자습서에서는 JavaMail 버전 1.5 이상이 필요합니다. 이 절차는 JavaMail 버전 1.6.1을 사용하여 테스트되었습니다.

1. 웹 브라우저에서 [Jakarta Activation GitHub 페이지](https://github.com/eclipse-ee4j/jaf/releases)로 이동하고 [JavaBeans Activation Framework 1.2.1 Final Release](https://github.com/eclipse-ee4j/jaf/releases/tag/1.2.1)에서 **jakarta.activation.jar**를 다운로드합니다.

1. 다음 단계를 수행하여 Eclipse에서 프로젝트를 만듭니다.

   1. Eclipse를 시작합니다.

   1. Eclipse에서, [**File**], [**New**], [**Java Project**]를 차례로 선택합니다.

   1. [**Create a Java Project**] 대화 상자에서, 프로젝트 이름을 입력하고 [**Next**]를 선택합니다.

   1. [**Java Settings**] 대화 상자에서, [**Libraries**] 탭을 선택합니다.

   1. **Classpath**를 선택하고 **외부 JAR 추가** 버튼을 사용하여 두 개의 외부 jar 파일 **javax.mail.jar** 및 **jakarta.activation.jar**를 추가합니다.

   1. [**Add External JARs**]를 선택합니다.

   1. JavaMail을 다운로드한 폴더로 이동합니다. `javax.mail.jar` 파일과 [**Open**]을 차례대로 선택합니다.

   1. [**Java Settings**] 대화 상자에서, [**Finish**]를 선택합니다.

1. Eclipse에서, [**Package Explorer**] 창에서 프로젝트를 확장합니다.

1. 프로젝트에서 [**src**] 디렉터리를 마우스 오른쪽 버튼으로 클릭한 후 [**New**], [**Class**]를 차례로 선택합니다.

1. [**New Java Class**] 대화 상자에서, [**Name**] 필드에 `AmazonSESSample`을 입력한 후 [**Finish**]를 선택합니다.

1. **AmazonSESSample.java**의 전체 내용을 다음 코드로 바꿉니다.

   ```
     1. import java.util.Properties;
     2. 
     3. import javax.mail.Message;
     4. import javax.mail.Session;
     5. import javax.mail.Transport;
     6. import javax.mail.internet.InternetAddress;
     7. import javax.mail.internet.MimeMessage;
     8. 
     9. public class AmazonSESSample {
    10. 
    11.     // Replace sender@example.com with your "From" address.
    12.     // This address must be verified.
    13.     static final String FROM = "sender@example.com";
    14.     static final String FROMNAME = "Sender Name";
    15.     
    16.     // Replace recipient@example.com with a "To" address. If your account 
    17.     // is still in the sandbox, this address must be verified.
    18.     static final String TO = "recipient@example.com";
    19.     
    20.     // Replace smtp_username with your Amazon SES SMTP user name.
    21.     static final String SMTP_USERNAME = "smtp_username";
    22.       
    23.     // The name of the Configuration Set to use for this message.
    24.     // If you comment out or remove this variable, you will also need to
    25.     // comment out or remove the header below.
    26.     static final String CONFIGSET = "ConfigSet";
    27.     
    28.     // Amazon SES SMTP host name. This example uses the US West (Oregon) region.
    29.     // See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints
    30.     // for more information.
    31.     static final String HOST = "email-smtp.us-west-2.amazonaws.com";
    32.     
    33.     // The port you will connect to on the Amazon SES SMTP endpoint. 
    34.     static final int PORT = 587;
    35.     
    36.     static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)";
    37.     
    38.     static final String BODY = String.join(
    39.             System.getProperty("line.separator"),
    40.             "<h1>Amazon SES SMTP Email Test</h1>",
    41.             "<p>This email was sent with Amazon SES using the ", 
    42.             "<a href='https://github.com/javaee/javamail'>Javamail Package</a>",
    43.             " for <a href='https://www.java.com'>Java</a>."
    44.         );
    45. 
    46.     public static void main(String[] args) throws Exception {
    47. 
    48.         // Create a Properties object to contain connection configuration information.
    49.         Properties props = System.getProperties();
    50.         props.put("mail.transport.protocol", "smtp");
    51.         props.put("mail.smtp.port", PORT); 
    52.         props.put("mail.smtp.starttls.enable", "true");
    53.         props.put("mail.smtp.auth", "true");
    54. 
    55.         // Create a Session object to represent a mail session with the specified properties. 
    56.         Session session = Session.getDefaultInstance(props);
    57. 
    58.         // Create a message with the specified information. 
    59.         MimeMessage msg = new MimeMessage(session);
    60.         msg.setFrom(new InternetAddress(FROM,FROMNAME));
    61.         msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
    62.         msg.setSubject(SUBJECT);
    63.         msg.setContent(BODY,"text/html");
    64.         
    65.         // Add a configuration set header. Comment or delete the 
    66.         // next line if you are not using a configuration set
    67.         msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET);
    68.             
    69.         // Create a transport.
    70.         Transport transport = session.getTransport();
    71. 
    72.         // Get the password 
    73.         String SMTP_PASSWORD = fetchSMTPPasswordFromSecureStorage();
    74.                     
    75.         // Send the message.
    76.         try
    77.         {
    78.             System.out.println("Sending...");
    79.             
    80.             // Connect to Amazon SES using the SMTP username and password you specified above.
    81.             transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
    82.             
    83.             // Send the email.
    84.             transport.sendMessage(msg, msg.getAllRecipients());
    85.             System.out.println("Email sent!");
    86.         }
    87.         catch (Exception ex) {
    88.             System.out.println("The email was not sent.");
    89.             System.out.println("Error message: " + ex.getMessage());
    90.         }
    91.         finally
    92.         {
    93.             // Close and terminate the connection.
    94.             transport.close();
    95.         }
    96.     }
    97. 
    98.     static String fetchSMTPPasswordFromSecureStorage() {
    99.         /* IMPLEMENT THIS METHOD */
   100.         // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/
   101.     }
   102. }
   ```

1. **AmazonSESSample.java**에서 다음 이메일 주소를 자체 값으로 대체합니다.
**중요**  
이메일 주소는 대/소문자를 구분합니다. 주소는 사용자가 확인한 것과 정확하게 동일해야 합니다.
   + *sender@example.com* - 'From' 이메일 주소로 대체합니다. 이 프로그램을 실행하기 전에 이 주소를 확인해야 합니다. 자세한 내용은 [Amazon SES에서 확인된 자격 증명](verify-addresses-and-domains.md) 단원을 참조하십시오.
   + *recipient@example.com* - 'To' 이메일 주소로 대체합니다. 계정이 아직 샌드박스에 있는 경우, 이 주소를 확인해야 계정을 사용할 수 있습니다. 자세한 내용은 [프로덕션 액세스 요청(Amazon SES 샌드박스에서 이동)](request-production-access.md) 단원을 참조하십시오.

1. **AmazonSESSample.java**에서 다음을 자체 값으로 대체합니다.
   + *smtp\$1username* – SMTP 사용자 이름 자격 증명으로 대체합니다. SMTP 사용자 이름 자격 증명은 식별 가능한 이름이 아니라 문자/숫자를 포함하는 20자 길이 문자열입니다.
   + *smtp\$1password* – ``fetchSMTPPasswordFromSecureStorage``를 구현하여 암호를 가져옵니다.

1. (선택 사항) *email-smtp.us-west-2.amazonaws.com* 이외의 AWS 리전 에서 Amazon SES SMTP 엔드포인트를 사용하려면 `HOST` 변수 값을 사용하려는 엔드포인트로 바꿉니다. Amazon SES를 사용할 수 있는 리전 목록은 *AWS 일반 참조*의 [Amazon Simple Email Service(Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)를 참조하세요.

1. (선택 사항) 이 이메일을 전송할 때 구성 세트를 사용하려면 *ConfigSet* 변수 값을 구성 세트의 이름으로 바꿉니다. 구성 세트에 대한 자세한 내용은 [Amazon SES에서 구성 세트 사용](using-configuration-sets.md) 단원을 참조하세요.

1. **AmazonSESSample.java**를 저장합니다.

1. 프로젝트를 빌드하려면 [**Project**]를 선택한 후 [**Build Project**]를 선택합니다. (이 옵션이 비활성화되어 있는 경우 자동 빌딩이 활성화된 것일 수 있습니다.)

1. 프로그램을 시작하고 이메일을 전송하려면 [**Run**]을 선택하고 다시 [**Run**]을 선택합니다.

1. 출력 결과를 검토합니다. 이메일이 성공적으로 전송되었으면 콘솔에 *'이메일이 발송되었습니다\$1'*가 표시됩니다. 완료되지 않은 경우 오류 메시지가 표시됩니다.

1. 수신자 주소의 이메일 클라이언트에 로그인합니다. 보낸 메시지가 도착해 있을 것입니다.

------
#### [ PHP  ]

이 예제에서는 SMTP 인터페이스를 사용하여 Amazon SES를 통해 이메일을 전송하기 위해 PHPMailer 클래스를 사용합니다.

다음 절차를 수행하기 전에 [Amazon Simple Email Service 설정](setting-up.md)의 작업을 완료해야 합니다. Amazon SES 를 설정하는 것 외에도 PHP로 이메일을 보내려면 다음과 같은 사전 요구 사항을 완료해야 합니다.

**사전 조건:**
+ **PHP 설치** – PHP는 [http://php.net/downloads.php](https://php.net/downloads.php)에서 다운로드할 수 있습니다. PHP를 설치한 후, 원하는 모든 명령 프롬프트에서 PHP를 실행할 수 있도록 PHP에 대한 경로를 환경 변수에 추가합니다.
+ **Composer 종속성 관리자 설치** – Composer 종속성 관리자를 설치한 후 PHPMailer 클래스와 클래스의 종속성을 다운로드하여 설치할 수 있습니다. Composer를 설치하려면 [https://getcomposer.org/download](https://getcomposer.org/download)의 설치 지침을 따르세요.
+ **PHPMailer 클래스 설치** – Composer를 설치한 후 다음 명령을 실행하여 다음과 같이 PHPMailer를 설치합니다.

  ```
  path/to/composer require phpmailer/phpmailer
  ```

  위의 명령에서 *path/to/*를 Composer를 설치한 경로로 바꿉니다.

**PHP를 사용하여 Amazon SES SMTP 인터페이스를 통해 이메일을 전송하려면**

1. **amazon-ses-smtp-sample.php**라는 파일을 만듭니다. 텍스트 편집기로 파일을 열고 다음 코드를 붙여 넣습니다.

   ```
    1. <?php
    2. 
    3. // Import PHPMailer classes into the global namespace
    4. // These must be at the top of your script, not inside a function
    5. use PHPMailer\PHPMailer\PHPMailer;
    6. use PHPMailer\PHPMailer\Exception;
    7. 
    8. // If necessary, modify the path in the require statement below to refer to the
    9. // location of your Composer autoload.php file.
   10. require 'vendor/autoload.php';
   11. 
   12. // Replace sender@example.com with your "From" address.
   13. // This address must be verified with Amazon SES.
   14. $sender = 'sender@example.com';
   15. $senderName = 'Sender Name';
   16. 
   17. // Replace recipient@example.com with a "To" address. If your account
   18. // is still in the sandbox, this address must be verified.
   19. $recipient = 'recipient@example.com';
   20. 
   21. // Replace smtp_username with your Amazon SES SMTP user name.
   22. $usernameSmtp = 'smtp_username';
   23. 
   24. // Specify a configuration set. If you do not want to use a configuration
   25. // set, comment or remove the next line.
   26. $configurationSet = 'ConfigSet';
   27. 
   28. // If you're using Amazon SES in a region other than US West (Oregon),
   29. // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
   30. // endpoint in the appropriate region.
   31. $host = 'email-smtp.us-west-2.amazonaws.com';
   32. $port = 587;
   33. 
   34. // The subject line of the email
   35. $subject = 'Amazon SES test (SMTP interface accessed using PHP)';
   36. 
   37. // The plain-text body of the email
   38. $bodyText =  "Email Test\r\nThis email was sent through the
   39.     Amazon SES SMTP interface using the PHPMailer class.";
   40. 
   41. // The HTML-formatted body of the email
   42. $bodyHtml = '<h1>Email Test</h1>
   43.     <p>This email was sent through the
   44.     <a href="https://aws.amazon.com/ses">Amazon SES</a> SMTP
   45.     interface using the <a href="https://github.com/PHPMailer/PHPMailer">
   46.     PHPMailer</a> class.</p>';
   47. 
   48. $mail = new PHPMailer(true);
   49. 
   50. try {
   51.     // Specify the SMTP settings.
   52.     $mail->isSMTP();
   53.     $mail->setFrom($sender, $senderName);
   54.     $mail->Username   = $usernameSmtp;
   55.     $mail->Password   = fetchSMTPPasswordFromSecureStorage();
   56.     $mail->Host       = $host;
   57.     $mail->Port       = $port;
   58.     $mail->SMTPAuth   = true;
   59.     $mail->SMTPSecure = 'tls';
   60.     $mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configurationSet);
   61. 
   62.     // Specify the message recipients.
   63.     $mail->addAddress($recipient);
   64.     // You can also add CC, BCC, and additional To recipients here.
   65. 
   66.     // Specify the content of the message.
   67.     $mail->isHTML(true);
   68.     $mail->Subject    = $subject;
   69.     $mail->Body       = $bodyHtml;
   70.     $mail->AltBody    = $bodyText;
   71.     $mail->Send();
   72.     echo "Email sent!" , PHP_EOL;
   73. } catch (phpmailerException $e) {
   74.     echo "An error occurred. {$e->errorMessage()}", PHP_EOL; //Catch errors from PHPMailer.
   75. } catch (Exception $e) {
   76.     echo "Email not sent. {$mail->ErrorInfo}", PHP_EOL; //Catch errors from Amazon SES.
   77. }
   78. function fetchSMTPPasswordFromSecureStorage() {
   79. /* IMPLEMENT THIS METHOD */
   80. // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/
   81. }
   82. 
   83. ?>
   ```

1. **amazon-ses-smtp-sample.php**에서 다음을 자체 값으로 대체합니다.
   + *sender@example.com* – Amazon SES에서 확인한 이메일 주소로 바꿉니다. 자세한 내용은 [확인된 자격 증명](verify-addresses-and-domains.md) 단원을 참조하십시오. Amazon SES에서 이메일 주소는 대/소문자를 구분합니다. 입력하는 주소는 사용자가 확인한 것과 정확하게 동일해야 합니다.
   + *recipient@example.com* – 수신자의 주소로 바꿉니다. 계정이 아직 샌드박스에 있는 경우, 이 주소를 확인해야 계정을 사용할 수 있습니다. 자세한 내용은 [프로덕션 액세스 요청(Amazon SES 샌드박스에서 이동)](request-production-access.md) 단원을 참조하세요. 입력하는 주소는 사용자가 확인한 것과 정확하게 동일해야 합니다.
   + *smtp\$1username* – SMTP 사용자 이름 자격 증명으로 대체합니다. 이 자격 증명은 Amazon SES 콘솔의 [SMTP 설정](https://console.aws.amazon.com/ses/home?#smtp-settings:) 페이지에서 확인할 수 있습니다. 이 이름은 AWS 액세스 키 ID와 동일하지 **않습니다**. SMTP 사용자 이름 자격 증명은 식별 가능한 이름이 아니라 문자/숫자를 포함하는 20자 길이 문자열입니다.
   + *smtp\$1password* – ``fetchSMTPPasswordFromSecureStorage``를 구현하여 암호를 가져옵니다.
   + (선택 사항) *ConfigSet* – 이 이메일을 전송할 때 구성 세트를 사용하려면 이 값을 구성 세트의 이름으로 바꿉니다. 구성 세트에 대한 자세한 내용은 [Amazon SES에서 구성 세트 사용](using-configuration-sets.md) 단원을 참조하세요.
   + (선택 사항) *email-smtp.us-west-2.amazonaws.com* – 미국 서부(오리건) 이외의 리전에서 Amazon SES SMTP 엔드포인트를 사용하려면 사용하려는 리전의 Amazon SES SMTP 엔드포인트로 대체합니다. Amazon SES를 사용할 수 AWS 리전 있는의 SMTP 엔드포인트 URLs 목록은의 [Amazon Simple Email Service(Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)를 참조하세요*AWS 일반 참조*.

1. **amazon-ses-smtp-sample.php**를 저장합니다.

1. 프로그램을 실행하려면 **amazon-ses-smtp-sample.php**와 동일한 디렉터리에서 명령 프롬프트를 열고 **php amazon-ses-smtp-sample.php**를 입력합니다.

1. 출력 결과를 검토합니다. 이메일이 성공적으로 전송되었으면 콘솔에 *'이메일이 발송되었습니다\$1'*가 표시됩니다. 완료되지 않은 경우 오류 메시지가 표시됩니다.

1. 수신자 주소의 이메일 클라이언트에 로그인합니다. 보낸 메시지가 도착해 있을 것입니다.

------