2009-11-23 5 views
1

서블릿을 통해 전자 메일을 보내야했지만 많은 코드를 시도했지만 그 중 아무도 gmail 계정으로 작업하지 않았습니다.서블릿을 사용하여 전자 메일 보내기

java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 
     Properties props = new Properties(); 
     props.put("mail.transport.protocol", "smtp"); 
     props.put("mail.smtp.starttls.enable","true"); 
     props.put("mail.smtp.host", "smtp.gmail.com"); 
     props.put("mail.smtp.auth", "true"); 

     Authenticator auth = new SMTPAuthenticator(); 
     //auth = null; 
     Session sess = Session.getInstance(props, auth); 

     sess.setDebug(false); 
      // -- Create a new message -- 
      Message msg = new MimeMessage(sess); 

      // -- Set the FROM and TO fields -- 
      msg.setFrom(new InternetAddress("[email protected]")); 
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
      "sendtoemail", false)); 
      msg.setSubject("Test"); 
      msg.setText("Yippe"); 
      msg.setSentDate(new Date()); 
      Transport.send(msg); 

      public class SMTPAuthenticator extends javax.mail.Authenticator { 
      @Override 
      public PasswordAuthentication getPasswordAuthentication() { 
      String username = "[email protected]"; 
      String password = "mypass"; 
      return new PasswordAuthentication(username, password); 
      } 

은}

이 코드는

public static Email createMail(){ 
    Email email = SimpleEmail(); 


    email.setHostName(Settings.getValue("smtp.host")); 
    email.setSmtpPort(Integer.parseInt(Settings.getValue("smtp.port"))); 
    String username = Settings.getValue("smtp.user"); 
    if (username.length() > 0) { 
     email.setAuthentication(username, Settings.getValue("smtp.password")); 
    } 

    boolean useSSL = false; 
    try { 
     useSSL = Boolean.parseBoolean(Settings.getValue("smtp.ssl")); 
    } catch (Exception ex) { 
     // ignore - property not set 
    } 

    email.setSSL(useSSL); 
    email.setCharset("utf-8"); 

    return email; 
} 

public sendMail(String recipientEmail) { 
    Email email = createMail(); 
    email.addTo(recipientEmail); 
    email.setFrom("[email protected]"); 
    email.setSubject("Your subject herE"); 
    email.setMsg("Your message here"); 
    email.send(); 
} 

답변

3

가 발생합니다. 또한 예외에서 유용한 정보의 양을 감소 초래 몬즈 이메일 스위칭 - 다음 행을 제외 로그에서 존재하지 않기 때문에 더 이상 :

nested exception is: 
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: 
    sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 

이 경우의 실제 리드 중첩 이내 예외.

해결하려면 JVM 키 저장소에 전자 메일 서버 인증서를 설치해야합니다. 디폴트의 ​​키스트 아의 위치는, Java의 배포에 의존합니다. 제 경우에는 /etc/java-6-sun/security/cacert

인증서를 추가 한 후 인증이 성공했습니다.

+0

어떻게 이것을 my..netbeans 프로젝트에 추가합니까? – user217029

+0

을 다운로드하여 빌드 경로에 추가하십시오. – Bozho

4

commons-email 그냥이 예외를 еliminate하지 않습니다 평민 - 이메일로 전환하여 javax.mail.MessagingException: Could not convert socket to TLS 예외를