[java] Javamail을 사용하여 이메일에 첨부 파일 압축하기

이메일에 파일을 첨부할 때, 일부 파일이 너무 크면 전송하는 것이 어려울 수 있습니다. 이 때, 파일을 압축하여 크기를 줄일 수 있습니다. 이 문서에서는 Javamail 라이브러리를 사용하여 이메일에 첨부 파일을 압축하는 방법을 알아보겠습니다.

1. 라이브러리 추가

먼저, 프로젝트의 의존성에 Javamail 라이브러리를 추가해야 합니다. Maven을 사용한다면, pom.xml 파일에 다음 의존성을 추가합니다:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail.smime</artifactId>
    <version>1.6.2</version>
</dependency>

Gradle을 사용한다면, build.gradle 파일에 다음 의존성을 추가합니다:

implementation 'javax.mail:javax.mail-api:1.6.2'
implementation 'com.sun.mail:javax.mail:1.6.2'
implementation 'com.sun.mail:javax.mail.smime:1.6.2'

의존성을 추가한 후, 프로젝트를 다시 빌드해주세요.

2. 파일 압축하기

압축할 파일을 ZipOutputStream을 사용하여 압축할 수 있습니다. 다음은 파일을 압축하는 예시 코드입니다:

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileCompressionExample {
    public static void compressFiles(File[] files, String zipFileName) {
        try {
            FileOutputStream fos = new FileOutputStream(zipFileName);
            ZipOutputStream zos = new ZipOutputStream(fos);

            for (File file : files) {
                if (file.isFile()) {
                    FileInputStream fis = new FileInputStream(file);
                    zos.putNextEntry(new ZipEntry(file.getName()));

                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) >= 0) {
                        zos.write(buffer, 0, length);
                    }

                    zos.closeEntry();
                    fis.close();
                }
            }

            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        File[] files = {new File("file1.txt"), new File("file2.txt")};
        String zipFileName = "compressed.zip";

        compressFiles(files, zipFileName);
    }
}

위 예시 코드에서는 compressFiles 메소드를 사용하여 어레이 형태의 파일들을 압축하여 지정한 파일 이름으로 저장합니다. 이 예시 코드에서는 file1.txtfile2.txtcompressed.zip으로 압축합니다.

3. 압축 파일 첨부하기

Javamail을 사용하여 이메일에 파일을 첨부할 수 있습니다. 다음은 이메일에 압축 파일을 첨부하는 예시 코드입니다:

import jakarta.mail.*;
import jakarta.mail.internet.*;

import java.util.Properties;

public class EmailExample {
    public static void sendEmailWithAttachment(String host, String port, String fromAddress, String toAddress, String subject, String body, String attachmentPath) {
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);

        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromAddress));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            message.setSubject(subject);

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachmentPath);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(source.getName());
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String host = "smtp.example.com";
        String port = "587";
        String fromAddress = "user@example.com";
        String toAddress = "recipient@example.com";
        String subject = "이메일 첨부 파일 압축 예시";
        String body = "안녕하세요, 첨부 파일 압축 예시입니다.";
        String attachmentPath = "compressed.zip";

        sendEmailWithAttachment(host, port, fromAddress, toAddress, subject, body, attachmentPath);
    }
}

위 예시 코드에서는 sendEmailWithAttachment 메소드를 사용하여 이메일에 압축 파일을 첨부합니다. 이메일의 호스트, 포트, 보내는 사람 주소와 받는 사람 주소, 제목, 본문, 첨부 파일 경로를 파라미터로 전달합니다. 이 예시 코드에서는 smtp.example.com 호스트와 587 포트를 사용하며, 보내는 사람 주소와 받는 사람 주소는 각각 user@example.comrecipient@example.com으로 설정하였습니다.

이제 Javamail을 사용하여 이메일에 첨부 파일을 압축하는 방법을 배웠습니다. 압축하여 파일 크기를 줄여 이메일을 보내면, 더 효율적인 전송이 가능해집니다.

참고 자료