SMTP (Simple Mail Transfer Protocol) 프로토콜 이란?
- 인터넷에서 이메일을 보내기 위해 이용되는 프로토콜
- 송신자와 수신자 간의 연결이 성립되면 이메일을 보낼 수 있다.
사용중인 이메일 (필자는 naver 사용) 에서 SMTP 설정 사용으로 변경
javax.mail pom.xml
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
Email Properties 설정
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "호스트 정보");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.port", "포트번호");
Authenticator auth = new EmailAuthentication();
Session session = Session.getDefaultInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
try {
InternetAddress toEmailAddress = new InternetAddress("receiver@email.com);
msg.setSentDate(new Date());
InternetAddress from = new InternetAddress();
from = new InternetAddress("sender@email.com");
msg.setFrom(from);
msg.setRecipient(Message.RecipientType.TO, toEmailAddress);
msg.setSubject("이메일 제목", "UTF-8");
// msg.setText("이메일 본문", "UTF-8");
msg.setHeader("content-Type", "text/html");
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(email.getContent(), "text/html; charset=utf-8");
// Body 형식으로 이메일 본문 전송
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
msg.setContent(multipart);
javax.mail.Transport.send(msg);
} catch (AddressException addr_e) {
addr_e.printStackTrace();
} catch (MessagingException msg_e) {
msg_e.printStackTrace();
}
이메일 본문에 html 형식의 string 문자열을 담아서 보내면 html 형태로 담겨서 보내진다
style 태그는 먹히지 않으므로 body 태그 안에서 직접 적용해주어야 한다.
'JAVA' 카테고리의 다른 글
Socket Programming (0) | 2022.05.10 |
---|---|
InetAddress 클래스 (0) | 2022.05.05 |
Retrofit2 (Java) (0) | 2022.04.02 |
JSON 변환 라이브러리 (Gson,Jackson) (0) | 2022.03.17 |
Optional 클래스 (0) | 2021.07.14 |