2009-11-23 90 views
1

我必須通過一個servlet發送一封電子郵件,我已經嘗試了一堆代碼,但是他們都沒有使用gmail帳戶,任何想法?使用servlet發送電子郵件

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); 
      } 

}

此代碼拋出javax.mail.MessagingException: Could not convert socket to TLS 異常

回答

3

使用commons-email

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(); 
} 
+0

如何將此項添加到my..netbeans項目中? – user217029 2009-11-23 14:21:56

+0

下載jar並將其添加到構建路徑。 – Bozho 2009-11-23 14:27:19

4

只需切換到公共電子郵件不會еliminate此異常。

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

我添加證書後,驗證成功。