Amazon SES SMTP 인터페이스를 통해 프로그래밍 방식으로 이메일 보내기 - Amazon Simple Email Service

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

Amazon SES SMTP 인터페이스를 통해 프로그래밍 방식으로 이메일 보내기

Amazon SES SMTP 인터페이스를 사용하여 이메일을 보내려면 SMTP -enabled 프로그래밍 언어, 이메일 서버 또는 애플리케이션을 사용할 수 있습니다. 시작하기 전에 Amazon Simple Email Service 설정의 작업을 완료해야 합니다. 또한 다음과 같은 정보가 필요합니다.

코드 예시

SMTP-enabled 프로그래밍 언어를 사용하여 Amazon SES SMTP 인터페이스에 액세스할 수 있습니다. Amazon SES SMTP 호스트 이름 및 포트 번호를 SMTP 자격 증명과 함께 제공한 다음 프로그래밍 언어의 일반 SMTP 함수를 사용하여 이메일을 보냅니다.

Amazon Elastic Compute Cloud (AmazonEC2) 는 기본적으로 포트 25를 통한 이메일 트래픽을 제한합니다. EC2Amazon에서 SMTP 엔드포인트를 통해 이메일을 보낼 때 시간 초과를 방지하기 위해 이러한 제한을 제거하도록 요청할 수 있습니다. 자세한 내용은 Amazon EC2 인스턴스 또는 AWS Lambda 함수에서 포트 25에 대한 제한을 제거하려면 어떻게 해야 합니까? 를 참조하십시오. AWS 지식 센터에서.

이 섹션의 Java용 코드 예제를 참조하고 포트 587을 PHP 사용하여 이 문제를 방지하십시오.

참고

이러한 자습서에서는 수신 여부를 확인할 수 있도록 자신에게 이메일을 발송합니다. 추가 실험 또는 부하 테스트가 필요한 경우 Amazon SES 메일박스 시뮬레이터를 사용하십시오. 사서함 시뮬레이터로 전송되는 이메일은 전송 할당량이나 반송 메일 및 수신 거부 발생률에 포함되지 않습니다. 자세한 내용은 수동으로 메일박스 시뮬레이터 사용 단원을 참조하십시오.

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

주의

SESAmazon은 정적 자격 증명을 사용하지 않는 것이 좋습니다. 소스 코드에서 하드 코딩된 자격 증명을 제거하여 보안 태세를 개선하는 방법을 AWS Secrets Manager알아보려면 를 참조하십시오. 이 자습서는 프로덕션 환경이 아닌 환경에서 Amazon SES SMTP 인터페이스를 테스트하기 위한 목적으로만 제공됩니다.

Java

이 예제에서는 IDEEclipse와 JavaMail API를 사용하여 인터페이스를 SES 사용하여 Amazon을 통해 이메일을 보냅니다. SMTP

다음 절차를 수행하기 전에 Amazon Simple Email Service 설정의 작업을 완료합니다.

Java와 Amazon SES SMTP 인터페이스를 사용하여 이메일을 보내려면
  1. 웹 브라우저에서 해당 JavaMail GitHub 페이지로 이동합니다. 자산에서 javax.mail.jar를 선택하여 최신 버전을 다운로드합니다. JavaMail

    중요

    이 자습서에는 버전 1.5 이상이 필요합니다 JavaMail . 이 절차는 JavaMail 버전 1.6.1을 사용하여 테스트되었습니다.

  2. 웹 브라우저에서 자카르타 활성화 GitHub 페이지로 이동한 다음 JavaBeans 활성화 프레임워크 1.2.1 최종 릴리스에서 jakarta.activation.jar를 다운로드합니다.

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

    1. Eclipse를 시작합니다.

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

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

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

    5. 클래스 경로를 선택하고 외부 추가 버튼을 사용하여 두 개의 외부 jar 파일인 javax.mail.jar 및 jakarta.activation.jar를 추가합니다. JARs

    6. [외부 JARs 추가] 를 선택합니다.

    7. 다운로드한 폴더를 JavaMail 탐색합니다. javax.mail.jar 파일과 [Open]을 차례대로 선택합니다.

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

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

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

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

  7. mazonSESSample.java의 전체 내용을 다음 코드로 바꾸십시오.

    import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class AmazonSESSample { // Replace sender@example.com with your "From" address. // This address must be verified. static final String FROM = "sender@example.com"; static final String FROMNAME = "Sender Name"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. static final String TO = "recipient@example.com"; // Replace smtp_username with your Amazon SES SMTP user name. static final String SMTP_USERNAME = "smtp_username"; // The name of the Configuration Set to use for this message. // If you comment out or remove this variable, you will also need to // comment out or remove the header below. static final String CONFIGSET = "ConfigSet"; // Amazon SES SMTP host name. This example uses the US West (Oregon) region. // See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints // for more information. static final String HOST = "email-smtp.us-west-2.amazonaws.com"; // The port you will connect to on the Amazon SES SMTP endpoint. static final int PORT = 587; static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)"; static final String BODY = String.join( System.getProperty("line.separator"), "<h1>Amazon SES SMTP Email Test</h1>", "<p>This email was sent with Amazon SES using the ", "<a href='https://github.com/javaee/javamail'>Javamail Package</a>", " for <a href='https://www.java.com'>Java</a>." ); public static void main(String[] args) throws Exception { // Create a Properties object to contain connection configuration information. Properties props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", PORT); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); // Create a Session object to represent a mail session with the specified properties. Session session = Session.getDefaultInstance(props); // Create a message with the specified information. MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(FROM,FROMNAME)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); msg.setSubject(SUBJECT); msg.setContent(BODY,"text/html"); // Add a configuration set header. Comment or delete the // next line if you are not using a configuration set msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET); // Create a transport. Transport transport = session.getTransport(); // Get the password String SMTP_PASSWORD = fetchSMTPPasswordFromSecureStorage(); // Send the message. try { System.out.println("Sending..."); // Connect to Amazon SES using the SMTP username and password you specified above. transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD); // Send the email. transport.sendMessage(msg, msg.getAllRecipients()); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); } finally { // Close and terminate the connection. transport.close(); } } static String fetchSMTPPasswordFromSecureStorage() { /* IMPLEMENT THIS METHOD */ // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/ } }
  8. mazonSESSample.java에서 다음 이메일 주소를 원하는 값으로 바꾸십시오.

    중요

    이메일 주소는 대/소문자를 구분합니다. 주소는 사용자가 확인한 것과 정확하게 동일해야 합니다.

    • sender@example.com — “보낸 사람” 이메일 주소로 바꾸십시오. 이 프로그램을 실행하기 전에 이 주소를 확인해야 합니다. 자세한 내용은 Amazon SES에서 확인된 자격 증명 단원을 참조하십시오.

    • recipient@example.com — “받는 사람” 이메일 주소로 바꾸십시오. 계정이 아직 샌드박스에 있는 경우, 이 주소를 확인해야 계정을 사용할 수 있습니다. 자세한 내용은 프로덕션 액세스 요청 (Amazon SES 샌드박스 밖으로 이동) 단원을 참조하십시오.

  9. mazonSESSample.java에서 다음을 사용자 고유의 값으로 바꾸십시오.

    • smtp_username — SMTP 사용자 이름 자격 증명으로 바꾸십시오. SMTP사용자 이름 자격 증명은 20자의 문자와 숫자로 구성된 문자열이며 알아들을 수 있는 이름이 아니라는 점에 유의하십시오.

    • smtp_password — 암호를 `fetchSMTPPasswordFromSecureStorage` 가져오도록 구현합니다.

  10. (선택 사항) AWS 리전 다른 곳에서 Amazon SES SMTP 엔드포인트를 사용하려는 경우 email-smtp.us-west-2.amazonaws.com변수 HOST 값을 사용하려는 엔드포인트로 변경하십시오. SESAmazon을 이용할 수 있는 지역 목록은 의 Amazon 단순 이메일 서비스 (AmazonSES) 를 참조하십시오 AWS 일반 참조.

  11. (선택 사항) 이 이메일을 보낼 때 구성 세트를 사용하려면 변수 값을 변경하십시오.ConfigSet 구성 집합의 이름으로 구성 세트에 대한 자세한 내용은 Amazon에서 구성 세트 사용 SES 단원을 참조하세요.

  12. mazonSESSample.java를 저장합니다.

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

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

  15. 출력 결과를 검토합니다. 이메일이 성공적으로 전송되면 콘솔에 “이메일 전송 완료!” 가 표시됩니다. 그렇지 않으면 오류 메시지가 표시됩니다.

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

PHP

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

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

사전 조건:
  • 설치 PHP — http://php.net/downloads.php PHP 에서 확인할 수 있습니다. PHP설치한 후 환경 변수에 경로를 추가하면 모든 명령 PHP 프롬프트에서 실행할 수 있습니다. PHP

  • Composer 종속성 관리자 설치 - Composer 종속성 관리자를 설치한 후 PHPMailer 클래스와 해당 종속성을 다운로드하고 설치할 수 있습니다. Composer를 설치하려면 https://getcomposer.org/download의 설치 지침을 따르세요.

  • PHPMailer클래스 설치 - Composer를 설치한 후 다음 명령을 실행하여 설치합니다. PHPMailer

    path/to/composer require phpmailer/phpmailer

    이전 명령에서 다음을 대체하십시오.path/to/ Composer를 설치한 경로를 사용하십시오.

Amazon SES SMTP 인터페이스를 사용하여 이메일을 보내려면 PHP
  1. amazon-ses-smtp-sample.php라는 이름의 파일을 생성하십시오. 텍스트 편집기로 파일을 열고 다음 코드를 붙여 넣습니다.

    <?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // If necessary, modify the path in the require statement below to refer to the // location of your Composer autoload.php file. require 'vendor/autoload.php'; // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. $sender = 'sender@example.com'; $senderName = 'Sender Name'; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. $recipient = 'recipient@example.com'; // Replace smtp_username with your Amazon SES SMTP user name. $usernameSmtp = 'smtp_username'; // Specify a configuration set. If you do not want to use a configuration // set, comment or remove the next line. $configurationSet = 'ConfigSet'; // If you're using Amazon SES in a region other than US West (Oregon), // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP // endpoint in the appropriate region. $host = 'email-smtp.us-west-2.amazonaws.com'; $port = 587; // The subject line of the email $subject = 'Amazon SES test (SMTP interface accessed using PHP)'; // The plain-text body of the email $bodyText = "Email Test\r\nThis email was sent through the Amazon SES SMTP interface using the PHPMailer class."; // The HTML-formatted body of the email $bodyHtml = '<h1>Email Test</h1> <p>This email was sent through the <a href="https://aws.amazon.com/ses">Amazon SES</a> SMTP interface using the <a href="https://github.com/PHPMailer/PHPMailer"> PHPMailer</a> class.</p>'; $mail = new PHPMailer(true); try { // Specify the SMTP settings. $mail->isSMTP(); $mail->setFrom($sender, $senderName); $mail->Username = $usernameSmtp; $mail->Password = fetchSMTPPasswordFromSecureStorage(); $mail->Host = $host; $mail->Port = $port; $mail->SMTPAuth = true; $mail->SMTPSecure = 'tls'; $mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configurationSet); // Specify the message recipients. $mail->addAddress($recipient); // You can also add CC, BCC, and additional To recipients here. // Specify the content of the message. $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $bodyHtml; $mail->AltBody = $bodyText; $mail->Send(); echo "Email sent!" , PHP_EOL; } catch (phpmailerException $e) { echo "An error occurred. {$e->errorMessage()}", PHP_EOL; //Catch errors from PHPMailer. } catch (Exception $e) { echo "Email not sent. {$mail->ErrorInfo}", PHP_EOL; //Catch errors from Amazon SES. } function fetchSMTPPasswordFromSecureStorage() { /* IMPLEMENT THIS METHOD */ // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/ } ?>
  2. amazon-ses-smtp-sample.php에서 다음을 원하는 값으로 바꾸십시오.

    • sender@example.com — Amazon에서 확인한 이메일 주소로 SES 대체하십시오. 자세한 내용은 확인된 자격 증명 단원을 참조하십시오. SESAmazon의 이메일 주소는 대소문자를 구분합니다. 입력하는 주소는 사용자가 확인한 것과 정확하게 동일해야 합니다.

    • recipient@example.com — 수신자 주소로 대체하십시오. 계정이 아직 샌드박스에 있는 경우, 이 주소를 확인해야 계정을 사용할 수 있습니다. 자세한 내용은 프로덕션 액세스 요청 (Amazon SES 샌드박스 밖으로 이동) 단원을 참조하세요. 입력하는 주소는 사용자가 확인한 것과 정확하게 동일해야 합니다.

    • smtp_username — Amazon SES 콘솔의 SMTP설정 페이지에서 받은 SMTP 사용자 이름 자격 증명으로 대체하십시오. 이 이름은 AWS 액세스 키 ID와 동일하지 않습니다. SMTP사용자 이름 자격 증명은 20자의 문자와 숫자로 구성된 문자열이며, 알아들을 수 있는 이름이 아니라는 점에 유의하십시오.

    • smtp_password — 암호를 `fetchSMTPPasswordFromSecureStorage` 가져오도록 구현합니다.

    • (선택 사항) ConfigSet — 이 이메일을 보낼 때 구성 세트를 사용하려면 이 값을 구성 집합의 이름으로 바꾸십시오. 구성 세트에 대한 자세한 내용은 Amazon에서 구성 세트 사용 SES 단원을 참조하세요.

    • (선택 사항) email-smtp.us-west-2.amazonaws.com — 미국 서부 (오레곤) 이외의 지역에서 Amazon SES SMTP 엔드포인트를 사용하려면 이 엔드포인트를 사용하려는 지역의 Amazon SES SMTP 엔드포인트로 대체하십시오. SESAmazon을 사용할 수 AWS 리전 있는 곳의 SMTP 엔드포인트 URLs 목록은 의 Amazon 단순 이메일 서비스 (AmazonSES) 를 참조하십시오 AWS 일반 참조.

  3. amazon-ses-smtp-sample.php를 저장하세요.

  4. 프로그램을 amazon-ses-smtp-sample실행하려면.php와 같은 디렉터리에서 명령 프롬프트를 연 다음 다음을 입력합니다. php amazon-ses-smtp-sample.php

  5. 출력 결과를 검토합니다. 이메일이 성공적으로 전송되면 콘솔에 “이메일 전송 완료!” 가 표시됩니다. 그렇지 않으면 오류 메시지가 표시됩니다.

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