인터넷에 gmail을 이용한 예제가 많아서 따라해 보았지만
gmail 보안설정 문제인지 제대로 실행이 되지 않았다.
혹시나하고 네이버랑 학교 메일 계정으로 바꿔봤는데 메일이 보내진다 !!
학교 계정의 경우 보내는 사람에 적힐 메일주소와 실제 smtp 서버를 사용할 계정이 달라도 상관없었는데
네이버의 경우 두개가 다르면 메일이 보내지지 않는다.
실제 프로젝트에는 학교 계정을 이용했다.
0. 사용할 메일 계정 SMTP서버명 알아내기 (네이버 - 환경설정 -POP3/IMAP 설정)
1. Java Mail 라이브러리 추가
2. SendMail 코드에 필요한 정보 입력 (메일주소, 서버아이디, 비밀번호 등)
1. pom.xml : Meaven Dendency 설정
javax.mail 1.4.7
2. SendMail.java
public class SendMail { public SendMail(String subject, String content){ final String toMail = "받는사람메일"; final String fromMail = "보내는사람메일"; final String fromMailUser = "보내는사람이름"; final String fromMailID = "사용할 smtp id"; final String password = "smtp 비밀번호"; Properties props = System.getProperties(); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //SSL props.put("mail.smtp.host", "smtp서버명"); // ex.stmp.naver.com props.put("mail.smtp.port", "465"); props.put("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(fromMailID, password); } }; Session session = Session.getInstance(props, auth); try { MimeMessage msg = new MimeMessage(session); msg.addHeader("Content-type", "text/HTML charset=UTF-8"); msg.addHeader("format", "flowed"); msg.addHeader("Content-Transfer-Encoding", "8bit"); msg.setFrom(new InternetAddress(fromMail , fromMailUser)); msg.setSubject(subject, "UTF-8") msg.setText(content, "UTF-8"); msg.setSentDate(new Date()); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail)); Transport.send(msg); System.out.println("suceess"); } catch (Exception e) { System.out.println("error"); e.printStackTrace(); } } }
보안연결 방식을 SSL 대신 TLS로 하려면 Properties props 부분을 바꿔주면 된다.
Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable","true"); //TTLS props.put("mail.smtp.host", "smtp 서버명"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls", "true")
※ 참고한 사이트
JAVA | 인터넷 쿠키 허용하기 (URLConnection enable cookie) (0) | 2015.09.04 |
---|---|
JAVA | 웹페이지 HTML 소스 파싱 (0) | 2015.09.04 |
JAVA | 메일에 파일 첨부하기 (Java Mail API) (0) | 2015.09.04 |
JAVA | 메일내용에 HTML 태그 넣기 (Java Mail API) (0) | 2015.09.04 |
JAVA | XML 파싱 + Excel 파일로 내보내기 (0) | 2015.07.17 |
MFC | WMV파일 재생하기 (0) | 2014.11.15 |
MFC | Picture Control을 이미지 파일로 저장하기 (0) | 2014.11.15 |
MFC | Dialog 배경이미지 넣기 (0) | 2014.11.15 |