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

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

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

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

코드 예제

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

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

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

참고

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

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

주의

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

Java

이 예제에서는 SMTP 인터페이스를 사용하여 Amazon SES 를 통해 이메일을 보내기 위해 Eclipse IDEJavaMail API를 사용합니다.

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

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

    중요

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

  2. 웹 브라우저에서 Jakarta Activation GitHub 페이지로 이동하고 JavaBeans Activation Framework 1.2.1 Final Release에서 jakarta.activation.jar를 다운로드합니다.

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

    1. Eclipse를 시작합니다.

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

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

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

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

    6. [Add External 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. AmazonSESSample.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. AmazonSESSample.java에서 다음 이메일 주소를 자체 값으로 대체합니다.

    중요

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

  9. AmazonSESSample.java에서 다음을 자체 값으로 대체합니다.

    • smtp_username – SMTP 사용자 이름 자격 증명으로 대체합니다. SMTP 사용자 이름 자격 증명은 식별 가능한 이름이 아니라 문자/숫자를 포함하는 20자 길이 문자열입니다.

    • smtp_password`fetchSMTPPasswordFromSecureStorage`를 구현하여 암호를 가져옵니다.

  10. (선택 사항) email-smtp.us-west-2.amazonaws.com 이외의 AWS 리전 에서 Amazon SES SMTP 엔드포인트를 사용하려면 HOST 변수 값을 사용하려는 엔드포인트로 바꿉니다. Amazon SES를 사용할 수 있는 리전 목록은 AWS 일반 참조Amazon Simple Email Service(Amazon SES)를 참조하세요.

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

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

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

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

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

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

PHP

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

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

사전 조건:
  • PHP 설치 – PHP는 http://php.net/downloads.php에서 다운로드할 수 있습니다. PHP를 설치한 후, 원하는 모든 명령 프롬프트에서 PHP를 실행할 수 있도록 PHP에 대한 경로를 환경 변수에 추가합니다.

  • Composer 종속성 관리자 설치 – Composer 종속성 관리자를 설치한 후 PHPMailer 클래스와 클래스의 종속성을 다운로드하여 설치할 수 있습니다. Composer를 설치하려면 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라는 파일을 만듭니다. 텍스트 편집기로 파일을 열고 다음 코드를 붙여 넣습니다.

    <?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에서 확인한 이메일 주소로 바꿉니다. 자세한 내용은 확인된 자격 증명 단원을 참조하십시오. Amazon SES에서 이메일 주소는 대/소문자를 구분합니다. 입력하는 주소는 사용자가 확인한 것과 정확하게 동일해야 합니다.

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

    • smtp_username – SMTP 사용자 이름 자격 증명으로 대체합니다. 이 자격 증명은 Amazon SES 콘솔의 SMTP 설정 페이지에서 확인할 수 있습니다. 이 이름은 AWS 액세스 키 ID와 동일하지 않습니다. SMTP 사용자 이름 자격 증명은 식별 가능한 이름이 아니라 문자/숫자를 포함하는 20자 길이 문자열입니다.

    • smtp_password`fetchSMTPPasswordFromSecureStorage`를 구현하여 암호를 가져옵니다.

    • (선택 사항) ConfigSet – 이 이메일을 전송할 때 구성 세트를 사용하려면 이 값을 구성 세트의 이름으로 바꿉니다. 구성 세트에 대한 자세한 내용은 Amazon SES에서 구성 세트 사용 단원을 참조하세요.

    • (선택 사항) email-smtp.us-west-2.amazonaws.com – 미국 서부(오리건) 이외의 리전에서 Amazon SES SMTP 엔드포인트를 사용하려면 사용하려는 리전의 Amazon SES SMTP 엔드포인트로 대체합니다. Amazon SES를 사용할 수 AWS 리전 있는의 SMTP 엔드포인트 URLs 목록은의 Amazon Simple Email Service(Amazon SES)를 참조하세요AWS 일반 참조.

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

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

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

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