1
我無法執行公開可用於通過Gmail發送電子郵件的代碼。我認爲這可能是一個網絡問題,因爲我在工作,但我可以通過cmd
提示符ping smtp.gmail.com
來ping通Gmail。如何通過GMail使用SMTP時修復javax.mail.MessagingException?
這裏是我使用(從this page)代碼:
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
class tester {
public static void main(String args[]) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.stmp.user", "username of the sender");
//If you want you use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "password of the sender");
// If you want to use SSL
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "username";
String password = "password";
return new PasswordAuthentication("username","password");
}
});
String to = "[email protected]";
String from = "[email protected]";
String subject = "Testing...";
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("JAVA is the BEST");
Transport transport = session.getTransport("smtp");
transport.send(msg);
System.out.println("E-mail sent !");
} catch(Exception exc) {
System.out.println(exc);
}
}
}
我已經改變了用戶名和密碼字段是正確的。有什麼可能導致這種情況?我已經使用了我自己的代碼和許多其他公開可用的代碼,但是我得到了同樣的錯誤。我也嘗試通過端口587運行並收到相同的錯誤。
以下是錯誤:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is: java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at GoogleMail.sendMail(GoogleMail.java:45)
我無法使用telnet命令連接到SMTP服務器。 'telnet smtp.gmail.com 465'或'telnet smtp.gmail.com 587'我想這意味着我將無法使用Gmail作爲SMTP服務器。我從哪裏出發? – jeanqueq