반응형

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();
  }
}
 


반응형

+ Recent posts