QQ 메일 SMTP를 통한 이메일 전송
Java 애플리케이션에서 QQ 메일을 통해 이메일을 보내려면 SMTP 프로토콜과 인증 정보를 사용해야 합니다. 다음은 필수 구성 요소와 코드 예제입니다.
필수 설정 정보
- 발신자 이메일 주소: QQ 메일 주소 (예: user@qq.com)
- 클라이언트 인증 키: QQ 메일의 SMTP 서비스 활성화 후 발급받은 앱 비밀번호
- 수신자 이메일: 메일을 받을 대상 주소
- 제목 및 본문: 전송할 메시지의 subject와 content
의존성 추가
Maven 기반 프로젝트라면 아래 의존성을 pom.xml에 포함하세요.
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
SMTP 서비스 활성화 방법
- QQ 메일 웹사이트에 로그인합니다.
- 설정 → 계정 메뉴로 이동합니다.
- "POP3/IMAP/SMTP" 관련 옵션에서 SMTP 서비스를 활성화합니다.
- 보안 검증을 완료하고, 클라이언트 전용 인증 코드를 발급받습니다.
메일 전송 유틸리티 클래스
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class QQMailSender {
private static final String SMTP_HOST = "smtp.qq.com";
private static final int SMTP_PORT = 465;
private static final String SENDER_EMAIL = "your_email@qq.com";
private static final String AUTH_KEY = "your_auth_code_here";
public static void send(String recipient, String title, String body)
throws MessagingException {
Properties config = new Properties();
config.put("mail.transport.protocol", "smtp");
config.put("mail.smtp.host", SMTP_HOST);
config.put("mail.smtp.port", SMTP_PORT);
config.put("mail.smtp.auth", "true");
config.put("mail.smtp.ssl.enable", "true");
config.put("mail.debug", "true");
Session mailSession = Session.getInstance(config, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SENDER_EMAIL, AUTH_KEY);
}
});
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(SENDER_EMAIL));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
message.setSubject(title);
message.setText(body, "UTF-8");
Transport.send(message);
}
}
테스트 실행 코드
public class MailTest {
public static void main(String[] args) {
try {
QQMailSender.send(
"recipient@example.com",
"테스트 제목: Java에서 보낸 메일",
"이 메시지는 Java 애플리케이션을 통해 전송되었습니다."
);
System.out.println("메일 전송 성공!");
} catch (Exception e) {
System.err.println("전송 실패: " + e.getMessage());
e.printStackTrace();
}
}
}