2013-02-12 60 views
0

我使用像下面的代碼,用戶ID的用戶名用戶名 和密碼的代碼發送電子郵件給從我要去的地方發送郵件我無法從Java

Properties props = System.getProperties(); 
props.put("mail.smtp.starttls.enable", "true"); 
props.put("mail.smtp.host", host); 
props.setProperty("mail.transport.protocol", "smtps"); 
props.put("mail.smtp.user", userid); 
props.put("mail.smtp.password", password); 
props.put("mail.smtp.port", "465"); 
props.put("mail.smtps.auth", "true"); 
Session session = Session.getDefaultInstance(props, null); 
MimeMessage message = new MimeMessage(session); 
InternetAddress fromAddress = null; 
InternetAddress toAddress = null; 

try { 
fromAddress = new InternetAddress(from); 
toAddress = new InternetAddress(to); 
} catch (AddressException e) { 

e.printStackTrace(); 
} 

message.setFrom(fromAddress); 
message.setRecipient(RecipientType.TO, toAddress); 
message.setSubject(subject); 
message.setText(text); 

//SMTPSSLTransport transport =(SMTPSSLTransport)session.getTransport("smtps"); 

Transport transport = session.getTransport("smtps"); 
transport.connect(host, userid, password); 
transport.sendMessage(message, message.getAllRecipients()); 
transport.close(); 

郵箱的密碼,但它給我像

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; 
    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 
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972) 
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642) 

錯誤的任何一個建議我什麼問題,我的代碼..... 感謝ü提前.....

+0

看看這篇文章,他們所使用的端口587,而不是:http://www.mkyong.com/spring/spring-sending-e-mail-via-gmail-smtp-server-with-mailsender/ – 2013-02-12 13:25:24

回答

2
Properties props = new Properties(); 
      props.put("mail.smtp.auth", "true"); 
      props.put("mail.smtp.starttls.enable", "true"); 
      props.put("mail.smtp.host", "smtp.gmail.com"); 
      props.put("mail.smtp.port", "587"); 

這是屬性設置我已成功地用於發送使用Gmail帳戶的電子郵件。那麼你可以使用創建一個會話:

Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(emailAddress, password); 
       } 
       }); 

這是一個稍微不同的方法,但它的代碼工作我使用。