2009-11-23 93 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

我添加证书后,验证成功。