반응형
pom.xml 의존성 추가
<!-- aws-ses-sdk-->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-ses</artifactId>
<version>1.12.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
AwsSesConfig.class 작성
@Configuration
public class AwsSesConfig {
@Value("${aws.ses.access-key}")
private String accessKey;
@Value("${aws.ses.secret-key}")
private String secretKey;
@Bean
public AmazonSimpleEmailService amazonSimpleEmailService() {
final BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey, secretKey);
final AWSStaticCredentialsProvider awsStaticCredentialProvider = new AWSStaticCredentialsProvider(basicAWSCredentials);
return AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(awsStaticCredentialProvider)
.withRegion(Regions.AP_NORTHEAST_2).build();
}
}
application.yml에 키 추가
aws:
ses:
access-key: #액세스키 아이디
secret-key: #시크릿 엑세스키
Test 코드 작성
package com.example.demo.service;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.model.RawMessage;
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
@SpringBootTest
class SendEmailServiceTest {
@Autowired
AmazonSimpleEmailService amazonSimpleEmailService;
@Test
void fileTest() throws MessagingException {
final String SUBJECT = "가나다라 제목";
final String SENDER = "보내는사람 이메일주소";
final String RECIPIENT = "받는사람 이메일주소";
final String BODY_TEXT = "abcd내용";
final String BODY_HTML = "<h1>내용입니데이</h1>";
final String ATTACHMENT = "D:\\ZZZ\\test.png";
//final String CONFIGURATION_SET = "ConfigSet";
Session session = Session.getDefaultInstance(new Properties());
// Create a new MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Add subject, from and to lines.
message.setSubject(SUBJECT, "UTF-8");
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
// Create a multipart/alternative child container.
MimeMultipart msg_body = new MimeMultipart("alternative");
// Create a wrapper for the HTML and text parts.
MimeBodyPart wrap = new MimeBodyPart();
// Define the text part.
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
// Define the HTML part.
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(BODY_HTML,"text/html; charset=UTF-8");
// Add the text and HTML parts to the child container.
msg_body.addBodyPart(textPart);
msg_body.addBodyPart(htmlPart);
// Add the child container to the wrapper object.
wrap.setContent(msg_body);
// Create a multipart/mixed parent container.
MimeMultipart msg = new MimeMultipart("mixed");
// Add the parent container to the message.
message.setContent(msg);
// Add the multipart/alternative part to the message.
msg.addBodyPart(wrap);
// Define the attachment
MimeBodyPart att = new MimeBodyPart();
DataSource fds = new FileDataSource(ATTACHMENT);
att.setDataHandler(new DataHandler(fds));
att.setFileName(fds.getName());
// Add the attachment to the message.
msg.addBodyPart(att);
// Try to send the email.
try {
System.out.println("Attempting to send an email through Amazon SES "
+"using the AWS SDK for Java...");
// Print the raw email content on the console
PrintStream out = System.out;
message.writeTo(out);
// Send the email.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
RawMessage rawMessage =
new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest =
new SendRawEmailRequest(rawMessage);
// .withConfigurationSetName(CONFIGURATION_SET);
amazonSimpleEmailService.sendRawEmail(rawEmailRequest);
System.out.println("Email sent!");
// Display an error if something goes wrong.
} catch (Exception ex) {
System.out.println("Email Failed");
System.err.println("Error message: " + ex.getMessage());
ex.printStackTrace();
}
}
}
결과
공식문서 참고
https://docs.aws.amazon.com/ko_kr/ses/latest/DeveloperGuide/send-email-raw.html
반응형
'Server > AWS' 카테고리의 다른 글
[AWS API Gateway] route key, route 경로 제외한 path를 통합으로 연결하기 (0) | 2023.08.30 |
---|---|
[Svelte 앱 S3, CloudFront에 배포하기] 3. CloudFront 연결하기 (0) | 2021.08.23 |
[Svelte 앱 S3, CloudFront에 배포하기] 2. S3 버킷에 배포하기 (0) | 2021.08.23 |
[Svelte 앱 S3, CloudFront에 배포하기] 1. Svelte 앱 띄워보기 (0) | 2021.08.23 |
[AWS] Region 지역별 속도 확인 location latency (0) | 2020.07.05 |