반응형
spring을 이용해 메일 발송하는 샘플 코드 입니다.
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.1.5.RELEASE</version> </dependency> |
import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; public class MailUtil { private static Logger logger = LoggerFactory.getLogger(MailUtil.class); public static void sendMail(String subject, String address, String personal, String htmlBody, PrettyLog prettyLog) throws MessagingException, UnsupportedEncodingException { prettyLog.start("메일발송"); prettyLog.append("SUBJECT", subject); prettyLog.append("ADDRESS", address); prettyLog.append("PERSONAL", personal); prettyLog.append("BODY", htmlBody.substring(0, Math.min(10, htmlBody.length()))); JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(CoreConstants.MAIL_HOST); mailSender.setPassword(CoreConstants.MAIL_PW); mailSender.setPort(CoreConstants.MAIL_PORT); mailSender.setUsername(CoreConstants.MAIL_ID); if (mailSender.getPort() == 587) { Properties javaMailProperties = new Properties(); javaMailProperties.setProperty("mail.smtp.starttls.enable", "true"); mailSender.setJavaMailProperties(javaMailProperties); } MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, false, "UTF-8"); helper.setFrom(new InternetAddress("보내는사람메일주소", "보내는사람이름")); helper.setTo(new InternetAddress(address, personal)); helper.setSubject(subject); helper.setText(htmlBody, true); // helper.addAttachment("파일명", new File("파일 경로")); try { mailSender.send(msg); } catch (MailException ex) { prettyLog.append("ERROR", "메일발송 실패"); logger.error("메일발송실패", ex); } prettyLog.stop(); } } |
반응형
'java' 카테고리의 다른 글
java log4j.properties samlple (0) | 2019.05.03 |
---|---|
java 정규식 한글 검사 (0) | 2019.05.03 |
이니시스 이니페이 결제취소 오류. (0) | 2019.05.02 |
spring boot mysql connector java version property (0) | 2019.04.09 |
spring security headers frameOptions 선택적 disable (0) | 2019.03.19 |
spring boot favicon.ico (0) | 2019.03.09 |
java.lang.IllegalStateException: No Java compiler available for configuration options compilerClassName: [null] and compiler: [null] (0) | 2019.03.09 |
springboot mybatis-config.xml to Java Config (0) | 2019.03.08 |