다음은 Java와 JavaMail API를 사용하여 이메일을 전송하는 예제입니다. 이 예제에서는 파일 첨부, 송신자/수신자/참조/숨은 참조(BCC) 설정, HTML 본문을 포함한 이메일 전송을 포함하고 있습니다.
1. 의존성 추가 (Maven 사용 시)
xml
<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
2. Java 코드
java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
public class EmailSender {
public static void main(String[] args) {
// SMTP 서버 설정
final String host = "smtp.gmail.com"; // Gmail SMTP 서버
final String username = "your-email@gmail.com"; // 송신자 이메일
final String password = "your-app-password"; // Gmail 앱 비밀번호
String to = "recipient@example.com"; // 수신자
String cc = "cc@example.com"; // 참조
String bcc = "bcc@example.com"; // 숨은 참조
String subject = "JavaMail로 보내는 HTML 이메일"; // 제목
String body = "<h1>안녕하세요!</h1><p>이것은 <b>HTML 이메일</b> 입니다.</p>"; // HTML 본문
String filePath = "C:/path/to/your/file.txt"; // 첨부 파일 경로
// SMTP 설정 속성
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// 인증 정보 설정
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(to));
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
message.setSubject(subject);
// 본문과 파일 첨부를 위한 Multipart 객체 생성
Multipart multipart = new MimeMultipart();
// HTML 본문 추가
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(body, "text/html; charset=utf-8");
multipart.addBodyPart(htmlPart);
// 첨부 파일 추가
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(new File(filePath));
multipart.addBodyPart(attachmentPart);
// 메시지에 Multipart 설정
message.setContent(multipart);
// 이메일 전송
Transport.send(message);
System.out.println("이메일 전송 성공!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. 코드 설명
-
SMTP 서버 설정
- Gmail을 사용하려면 smtp.gmail.com을 설정하고 포트 587을 사용.
- TLS 보안을 활성화 (mail.smtp.starttls.enable = true).
- SMTP 인증 활성화 (mail.smtp.auth = true).
-
세션 생성
- Session.getInstance(props, new Authenticator()) 를 사용하여 인증 정보 포함.
-
이메일 메시지 생성
- MimeMessage 객체를 생성하고, 송신자/수신자/참조/숨은 참조 설정.
-
HTML 본문 추가
- MimeBodyPart에 HTML 컨텐츠를 설정.
-
파일 첨부
- MimeBodyPart를 사용해 파일을 첨부 (attachFile(new File(filePath))).
-
이메일 전송
- Transport.send(message) 를 통해 이메일을 전송.
4. Gmail SMTP 사용 시 주의사항
- Gmail에서 보안 수준이 높은 앱이 아닌 경우, 직접 로그인할 수 없습니다.
- Google 계정 보안 설정에서 앱 비밀번호(App Password) 를 생성하여 사용해야 합니다.
- 또는 OAuth 2.0 인증을 사용할 수도 있습니다.
|