본문 바로가기
infra/aws

[AWS SDK for JAVA] SES 버전 1.x에서 2.x로 마이그레이션

by moonsiri 2024. 6. 4.
728x90
반응형

AWS SDK for Java에서 SES(Simple Email Service)를 사용할 때, 버전 1.x에서 2.x로 마이그레이션하는 과정에 대해 설명하겠습니다. 버전 2.x는 많은 변경 사항과 개선된 기능을 제공하므로, 이를 통해 더 나은 성능과 유지보수성을 확보할 수 있습니다.

 

Overview

AWS SDK 버전 1.x는 `groupId`로 `com.amazonaws`를 사용하고, 버전 2.x는 `software.amazon.awssdk`를 사용합니다. 이는 패키지 구조의 변경을 의미하며, 코드 수정이 필요합니다.

 

Migration

Maven dependency

먼저, 프로젝트의 의존성을 변경해야 합니다. 다음은 Maven을 사용하는 경우의 예시입니다.

AWS SDK for Java 1.x의 SES)

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-ses</artifactId>
    <version>1.12.372</version>
</dependency>

AWS SDK for Java 2.x의 SES V1)

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>ses</artifactId>
    <version>2.25.64</version>
</dependency>

AWS SDK for Java 2.x의 SES V2)

 

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>sesv2</artifactId>
    <version>2.25.64</version>
</dependency>

 

 

Configuration

설정 클래스를 변경합니다. 버전 2.x에서는 새로운 인증 및 클라이언트 빌더를 사용합니다.

SDK V1)

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;

@Configuration
public class AwsSesConfiguration {

	@Bean
	public AmazonSimpleEmailService amazonSimpleEmailService() {
		BasicAWSCredentials credentials = new BasicAWSCredentials(username, password);
		return AmazonSimpleEmailServiceClientBuilder.standard()
				.withCredentials(new AWSStaticCredentialsProvider(credentials))
				.withRegion(Regions.valueOf(region))
			.build());
	}
   
}

SDK V2)

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ses.SesClient;
// import software.amazon.awssdk.services.sesv2.SesV2Client;

@Configuration
public class AwsSesConfiguration {

	@Bean
	public SesClient amazonSesClient() {	// SES V2 사용 시 SesV2Client
		AwsBasicCredentials credentials = AwsBasicCredentials.create(username, password);
		return SesClient.builder()
				.credentialsProvider(StaticCredentialsProvider.create(credentials))
				.region(Region.of(region))
			.build();
	}
}

 

Send email

SES 클라이언트의 사용법이 변경되었기 때문에 이메일을 보내는 로직을 변경해야합니다.

SDK V1)

import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.model.*;

	public void sendEmail(String sendEmailAddr, String personal, String receiverEmailAddr, String subject, String content, boolean isHtmlMail) throws UnsupportedEncodingException {
		// 받는사람
		Destination destination = new Destination().withToAddresses(receiverEmailAddr);
        
		// Create the subject and body of the message.
		Content subjectCont = new Content().withData(subject).withCharset("UTF_8");
		Content textBodyCont = new Content().withData(content).withCharset("UTF_8");
		Body body = new Body();

		if (isHtmlMail) { //HTML 메일
			body.setHtml(textBodyCont);
		} else {
			body.setText(textBodyCont);
		}
        
		// Create a message with the specified subject and body.
		Message message = new Message().withSubject(subjectCont).withBody(body);

		InternetAddress addr = new InternetAddress(sendEmailAddr, personal);
		// Assemble the email.
		SendEmailRequest request = new SendEmailRequest().withSource(addr.toString()).withDestination(destination).withMessage(message);

		SendEmailResult result = amazonSimpleEmailService.sendEmail(request);
		if (result.getSdkHttpMetadata().getHttpStatusCode() != 200) {
			throw new Exception(String.valueOf(result.getSdkHttpMetadata().getHttpStatusCode()));
		}
	}

SDK V2)

import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.ses.model.*;

	public void sendEmail(String sendEmailAddr, String personal, String receiverEmailAddr, String subject, String content, boolean isHtmlMail) throws UnsupportedEncodingException {
		// 받는사람
		Destination destination =  Destination.builder().toAddresses(receiverEmailAddr).build();

		// Create the subject and body of the message.
		Content subjectCont = Content.builder().charset("UTF_8").data(subject).build();
		Content textBodyCont = Content.builder().charset("UTF_8").data(content).build();
		
		Body body;
		if (isHtmlMail) { //HTML 메일
			body = Body.builder().html(textBodyCont).build();
		} else {
			body = Body.builder().text(textBodyCont).build();
		}

		// Create a message with the specified subject and body.
		Message message = Message.builder().subject(subjectCont).body(body).build();

		InternetAddress addr = new InternetAddress(sendEmailAddr, personal, "UTF_8");
		// Assemble the email.
		SendEmailRequest request = SendEmailRequest.builder().source(addr.toString()).destination(destination).message(message).build();

		SendEmailResponse response = amazonSesClient.sendEmail(request);
		if (!response.sdkHttpResponse().isSuccessful()) {
			throw new Exception(String.valueOf(response.sdkHttpResponse().statusCode()));
		}
	}

 

 


 

 

이 가이드는 AWS SDK 버전 1.x에서 2.x로 마이그레이션하는 과정에서 발생할 수 있는 주요 변경 사항을 다루고 있습니다. 이 외에도 코드의 다른 부분에서 추가적인 변경이 필요할 수 있으므로, AWS 공식 문서를 참고하여 모든 변경 사항을 반영하시기 바랍니다.

728x90
반응형

댓글