Preloader image
DDD

자바

이메일 전송 및 여러 개 파일 첨부 예제

작성자 관리자 (admin)
조회수 635
입력일 2025-03-18 05:50:36

이메일 전송 및 여러 개 파일 첨부 예제

다음은 Gmail SMTP 서버를 사용하여 이메일을 전송하는 코드입니다.

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import javax.activation.*;

public class EmailWithAttachments {
    public static void main(String[] args) {
        // SMTP 서버 설정
        final String host = "smtp.gmail.com";  // Gmail SMTP 서버
        final String port = "587"; // TLS 포트
        final String username = "your-email@gmail.com"; // 발신자 이메일
        final String password = "your-email-password"; // 앱 비밀번호 사용

        // 수신자 이메일 주소
        String toEmail = "receiver@example.com";

        // 이메일 속성 설정
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);

        // 인증 객체 생성
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 이메일 메시지 생성
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
            message.setSubject("파일 첨부 이메일 테스트");

            // 본문 내용
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText("안녕하세요. 여러 개의 파일을 첨부한 이메일입니다.");

            // 파일 첨부 부분
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);

            // 첨부할 파일 목록
            String[] filePaths = {"C:/path/to/file1.pdf", "C:/path/to/file2.jpg"};

            for (String filePath : filePaths) {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                File file = new File(filePath);
                if (file.exists()) {
                    attachmentPart.attachFile(file);
                    multipart.addBodyPart(attachmentPart);
                } else {
                    System.out.println("파일 없음: " + filePath);
                }
            }

            // 메시지에 첨부 추가
            message.setContent(multipart);

            // 이메일 전송
            Transport.send(message);
            System.out.println("이메일이 성공적으로 전송되었습니다!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}