Spring sendMail 연동 / spring sendmail example

북마크 추가

사전준비 

 

서버에 sendmail이 설치 되어 있어야 합니다.

* sendmail 설치 및 설정

바로가기 :: http://www.trandent.com/board/Etc/detail/729

 

1. maven pom.xml

 

javax.mail api를 사용하기 위해 dependency 추가

 

<dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.5.5</version>
  </dependency>

 

2. MailSender.java

 

package com.trandent.util;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSender {
private static String strMailServerPort = "25";
private static String strMailFrom = "admin@trandent.com"; //보내는 사람 메일 주소

public static Boolean sendMail(String strMailTo, String strTitle, String strContents) throws Exception {
Boolean result = true;
try {
Properties props = new Properties();
props.put("mail.smtp.host", "123.123.123.123"); // sendmail ip address
props.put("mail.smtp.port", strMailServerPort); // 25
props.put("mail.smtp.auth", "false");
Session msgSession = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(msgSession);
InternetAddress from = new InternetAddress(strMailFrom,"Trandent","UTF-8"); // (보내는사람 메일 주소 , 표시 할 이름 , 문자셋)

msg.setFrom(from);
InternetAddress to = new InternetAddress(strMailTo); // 받는사람 메일주소
msg.setRecipient(Message.RecipientType.TO, to);
msg.setSubject(strTitle); // 메일 제목
msg.setContent(strContents, "text/html; charset=UTF-8"); //메일 내용

Transport.send(msg);
} catch(MessagingException e) {
result = false;
System.out.println(e);
}
return result;
}
}

3. 사용방법

@ResponseBody
@RequestMapping(value = "/sendMail", method = RequestMethod.GET)
public String sendMail(HttpServletRequest req) throws Exception {
boolean result =MailSender.sendMail(foo@foo.com, "sendmail test title", "sendmail test contents");
String msg = "";
if(result)
msg = "success";
else
msg = "fail";
return msg;
}
 

 

 

 

 

 

 

 

 

 

 

AD
관리자
2016-06-23 21:57
SHARE