포스트 목록

2014년 10월 27일 월요일

[JAVA] SMTP를 이용한 메일전송 (네이버 서버 이용)

Cooker를 진행하다보니 중복가입 방지를 위한 코드전송이 필요하게 되었다.
네이버/구글 SMTP서버를 이용하여, 메일을 전송하는 방법을 사용한다.
Java 6부터는 javax.mail을 이용한다. activation.jar가 jre에 기본으로 포함되었다.

   import javax.mail.*;
   import javax.mail.internet.*;

   import java.util.Properties;

   Properties props = System.getProperties();
   props.put("mail.smtp.user" , "아이디");
   props.put("mail.smtp.host", "smtp.naver.com");
   props.put("mail.smtp.port", "465");
   props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.debug", "true");
   props.put("mail.smtp.socketFactory.port", "465");
   props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
   props.put("mail.smtp.socketFactory.fallback", "false");

   Session mailSession = Session.getInstance(props , null);
   Message msg = new MimeMessage(mailSession.getDefaultInstance(props, new SmtpAuthenticator()));

   InternetAddress to = new InternetAddress(email);                                    //수신자 주소 생성
   msg.setFrom(new InternetAddress(myMail));                                           //송신자 설정
   msg.setRecipient(javax.mail.Message.RecipientType.TO, to);                 //수신자 설정
   msg.setSubject(Title);                                                                                //제목 설정
   msg.setSentDate(new java.util.Date());                                                     //보내는 날짜 설정
   msg.setContent(Message, "text/html;charset=euc-kr");                            //내용 설정 (HTML 형식)

   Transport.send(msg);

   public class SmtpAuthenticator extends Authenticator{
         public SmtpAuthenticator(){
                  super();
         }

         public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication("아이디@naver.com", "비밀번호");
         }
   }

댓글 1개: