필요 라이브러리
//https://mvnrepository.com/artifact/com.sun.mail/javax.mail/1.6.2
// sendMail메소드를 static 맹글어 쓰면 아주 편하지용
import java.util.Map;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
public class MailUtil {
public static void sendMail(Map<String, String> mailDTO) {
System.out.println("JavaMail API Test 시작");
String subject = mailDTO.get("title");
String fromMail = mailDTO.get("fromMail");
String password = mailDTO.get("password");
String fromName = mailDTO.get("fromName");
// String toMail = "메렁"; // 콤마(,) 나열 가능
String toMail = mailDTO.get("toMail");
String contents = mailDTO.get("contents");
// mail contents
// StringBuffer contents = new StringBuffer();
// contents.append("<h1>인증번호:" + _code +"</h1>\n");
// contents.append("<p>Nice to meet you ~! :)</p><br>");
// mail properties
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.naver.com"); // use naver mail
props.put("mail.smtp.port", "465"); // set port
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true"); // use TLS
props.put("mail.smtps.ssl.checkserveridentity", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session mailSession = Session.getInstance(props,
new javax.mail.Authenticator() { // set authenticator
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromMail, password);
}
});
try {
MimeMessage message = new MimeMessage(mailSession);
// B(Base64) or Q(Quoted-Printabl) Encoding
message.setFrom(new InternetAddress(fromMail, MimeUtility.encodeText(fromName, "UTF-8", "B"))); // 한글의 경우 encoding 필요
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(toMail)
);
message.setSubject(subject);
message.setContent(contents.toString(), "text/html;charset=UTF-8"); // 내용 설정 (HTML 형식)
message.setSentDate(new java.util.Date());
Transport t = mailSession.getTransport("smtp");
t.connect(fromMail, password);
t.sendMessage(message, message.getAllRecipients());
t.close();
System.out.println("잘 보내졌어요 ~!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//위 클래스의 static 메소드 sendMail을 서블릿에서 필요한 곳에 써용
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import kr.pe.basic.util.MailUtil;
@Controller
@RequestMapping("/mail")
public class MailController {
@GetMapping(value ="/sendCheck",produces = "application/json;charset=utf-8")
@ResponseBody
public String sendMail(String toMail,HttpServletRequest request) throws Exception {
// 방법1
ServletContext context = request.getSession().getServletContext();
Properties prop = new Properties();
prop.load(context.getResourceAsStream("WEB-INF/properties/sample2.properties"));
/* 방법2
Reader reader= Resources.getResourceAsReader("/properties/sample.properties");
Properties prop = new Properties();
prop.load(reader);
*/
String contents = "<div style=text-align:center>" +
"<h1>난 최고의 프로그래머당</h1>" +
"<h2>난 최고의 프로그래머당</h2>" +
"<h3>난 최고의 프로그래머당</h3>" +
"<h4>난 최고의 프로그래머당</h4>" +
"<h5>난 최고의 프로그래머당</h5>" +
"<h6>난 최고의 프로그래머당</h6>" +
"<h5>난 최고의 프로그래머당</h5>" +
"<h4>난 최고의 프로그래머당</h4>" +
"<h3>난 최고의 프로그래머당</h3>" +
"<h2>난 최고의 프로그래머당</h2>" +
"<h1>난 최고의 프로그래머당</h1>" +
"<img src='//t2.gstatic.com/licensed-image?q=tbn:ANd9GcQpXsKoteBtiFMlWC2zNBqgHeDwDjKdnV4bNeZnKdn94_Q4gr7CVNbMlkENZZhGzL8I' width=300 height=300>" +
"</div>";
Map<String, String> mailDTO = new HashMap<String, String>();
mailDTO.put("title", "제목이디용");
mailDTO.put("fromMail", prop.getProperty("email"));
mailDTO.put("password", prop.getProperty("passwd"));
mailDTO.put("fromName","닉네임272");
mailDTO.put("toMail","dhtml@hanmail.net");
mailDTO.put("contents",contents);
MailUtil.sendMail(mailDTO);
return "OK 메일확인하세용";
}
}
// sample.properties 파일내용
// 자바소스에 넣으면 안 좋으니, 계정명과 암호는 따로 파일로 분리했어용
email=네이버메일계정
passwd=암호