我試圖使用Gmail smtp服務器從網頁發送電子郵件到我的電子郵件ID。我在stackoverflow上試過各種答案。不幸的是,他們都沒有工作。使用JavaMail API時沒有收到任何迴應
`public void sendMail(String msg){
Properties props= System.getProperties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtps.debug", "true");
props.put("mail.smtp.socketFactory.fallback", "false");
//props.put("mail.smtp.ssl.enable", "true");
//props.put("mail.transport.protocol", "smtp");
Authenticator authenticate= new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
};
@SuppressWarnings("deprecation")
Session mailSession= Session.getInstance(props, authenticate);
mailSession.setDebug(true);
Message mailMessage= new MimeMessage(mailSession);
try {
mailMessage.setFrom(new InternetAddress(mailFrom));
mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
mailMessage.setSubject(subject);
mailMessage.setText(msg);
Transport trans= mailSession.getTransport("smtp");
trans.connect("smtp.gmail.com", username, password);
trans.sendMessage(mailMessage, mailMessage.getAllRecipients());
trans.close();
} catch (Exception ex) {
Logger.getLogger(MailSender.class.getName()).log(Level.SEVERE, null, ex);
}
}`
我想上面寫的代碼
DEBUG: setDebug: JavaMail version 1.5.4 Info: DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] Info: DEBUG SMTP: useEhlo true, useAuth true Info: DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
而且,這是我得到的,沒有例外,沒有消息的輸出,而不是連一封電子郵件給我的電子郵件地址。 我參考聯機教程使用JavaMail API 1.5.4 Java 8和GlassFish Server作爲本地主機服務器。
請幫忙!!
修復這些[常見錯誤](https://javaee.github.io/javamail/FAQ#commonmistakes),請按照這些[Gmail說明](https://javaee.github.io/javamail/FAQ#gmail) ,如果它仍然不起作用,請嘗試這些[連接調試技巧](https://javaee.github.io/javamail/FAQ#condebug)。 –
因此它停止嘗試連接? –
@BillShannon感謝您的回覆,我刪除了常見的錯誤。但是這一次我得到這個:javax.mail.MessagingException:無法連接到SMTP主機:smtp.gmail.com,端口:465; – Cyrus