Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- springboot
- Kubernetes
- Java
- dbeaver
- LOG4J
- docker
- JPA
- VSCode
- IntelliJ
- Spring
- MySQL
- nodejs
- log4j2
- gradle
- Git
- NCP
- tibero
- jetbrains
- gson
- mybatis
- wildfly
- database
- nginx
- BPMN
- useEffect
- Windows
- kubectl
- JavaScript
- intellijIDEA
- react
Archives
- Today
- Total
두 손끝의 창조자
Java로 메일 전송하기 본문
SMTP 서버 설정정보로 세션을 흭득하고
MimeMessage에 세션을 가지고 메시지를 만들고
Transport 로 메시지를 전송한다.
세션을 만들때 default세션으로 가져오면 다른 계정에 대한 정보를 인지하지 않고 기본세션정보만 가져오기 때문에 유의해야한다.
import org.springframework.util.StringUtils;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MailSender {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MailSender.class);
private final String account;
private final String fromEmail;
private final List<String> toEmails;
private final String subject;
private final String content;
private final List<String> failMails = new ArrayList<>();
private final String regex = "^[_a-z0-9-]+(.[_a-z0-9-]+)*@(?:\\w+\\.)+\\w+$";
private final Pattern emailAddressPattern = Pattern.compile(regex);
private final String password;
private int sendSuccessCount;
private String errorMessage;
public MailSender(String account, String password, String fromEmail, List<String> toEmails, String subject, String content) {
this.account = account;
this.fromEmail = fromEmail;
this.toEmails = toEmails;
this.subject = subject;
this.content = content;
this.password = password;
}
public List<String> getFailMails() {
return failMails;
}
public int getSendSuccessCount() {
return sendSuccessCount;
}
public int getTotalToMails() {
return toEmails.size();
}
public InternetAddress createEmailAddress(String mailAddressString, String person, String encoding) {
try {
return new InternetAddress(mailAddressString, person, encoding);
} catch (Exception e) {
failMails.add(mailAddressString);
return null;
}
}
public InternetAddress createEmailAddress(String mailAddressString) {
try {
return new InternetAddress(mailAddressString);
} catch (Exception e) {
failMails.add(mailAddressString);
return null;
}
}
public List<InternetAddress> createEmailAddresses(List<String> mailAddressStrings) {
List<InternetAddress> mails = new ArrayList<>(mailAddressStrings.size());
for (String mailAddressString : mailAddressStrings) {
Matcher m = emailAddressPattern.matcher(mailAddressString);
if (!m.matches()) {
failMails.add(mailAddressString);
continue;
}
InternetAddress emailAddress = createEmailAddress(mailAddressString);
if (emailAddress != null)
mails.add(emailAddress);
}
return mails;
}
public void sendMail() {
Properties props = new Properties();
//네이버 웍스 메일 서버
props.put("mail.smtp.host", "smtp.worksmobile.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.trust", "smtp.worksmobile.com");
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
Message msg;
try {
Session session = getSession(props);
log.info(session.toString());
msg = new MimeMessage(session);
} catch (Exception e) {
errorMessage = e.getMessage();
return;
}
if (!StringUtils.hasText(content)) {
errorMessage = "내용이 없음";
return;
}
InternetAddress fromEmailAddress = createEmailAddress(account, fromEmail, "utf-8");
if (fromEmailAddress == null) {
errorMessage = "송신자 주소가 없음";
return;
}
List<InternetAddress> emailAddresses = createEmailAddresses(toEmails);
try {
msg.setFrom(fromEmailAddress);
msg.setRecipients(Message.RecipientType.TO, emailAddresses.toArray(new InternetAddress[0]));
msg.setSentDate(new Date());
msg.setSubject(subject);
msg.setContent(content, "text/html;charset=utf-8");
Transport.send(msg);
} catch (MessagingException e) {
errorMessage = e.getMessage();
return;
}
sendSuccessCount = emailAddresses.size();
}
public String getErrorMessage() {
return errorMessage;
}
private Session getSession(Properties props) {
// 삽질한 부분. 기본 세션을 가져오면 계정을 암만 바꿔도 같은 계정으로만 가져온다.
return Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(account, password);
}
});
}
public void failSendMail(String message) {
this.errorMessage = message;
}
}
반응형
Comments