본문 바로가기
Server/AWS

[AWS-SES/Spring]첨부파일 붙여서 메일 보내기

by 오늘의개발부 2022. 1. 4.
반응형

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

 

Amazon SES API를 사용하여 원시 이메일 보내기 - Amazon Simple Email Service Classic

이 규칙은 메시지 헤더가 아닌 메시지 봉투에 지정하는 이메일 주소에만 적용됩니다. SendRawEmail API를 사용하면 Source 및 Destinations 파라미터에 지정하는 주소가 봉투 발신자 및 수신자를 각각 정

docs.aws.amazon.com

 

반응형