The code:
public static void main(String[] args) {
try {
AuthenticatingSMTPClient c = new AuthenticatingSMTPClient();
c.setDefaultTimeout(10000);
c.connect("smtp.gmail.com", 587);
c.ehlo("localhost");
if (c.execTLS()) {
c.auth(AuthenticatingSMTPClient.AUTH_METHOD.PLAIN, "xxx@gmail.com", "xxx");
c.setSender("xxx@gmail.com");
c.addRecipient("yyy@yahoo.com.hk");
Writer w = c.sendMessageData();
if (w != null) {
SimpleSMTPHeader header = new SimpleSMTPHeader("xxx@gmail.com", "yyy@yahoo.com.hk", "Alert");
w.write(header.toString());
w.write("Alert test");
w.close();
if (!c.completePendingCommand()) {
throw new Exception("The email was failed to send. " + c.getReply() + c.getReplyString());
}
} else {
throw new Exception("The email was failed to send." + c.getReply() + c.getReplyString());
}
c.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
} else {
throw new Exception("STARTTLS was not accepted " + c.getReply() + " " + c.getReplyString());
}
c.logout();
c.disconnect();
} catch (Exception ex) {
System.err.println(ex.toString());
}
}
The result:
run:
java.net.SocketTimeoutException: Read timed out
BUILD SUCCESSFUL (total time: 13 seconds)
Why above code is timeout? Is it blocked me to use smtp by gmail? I checked that my username and password are both correct. And I found the example from http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/ and https://github.com/caarmen/network-monitor/blob/master/networkmonitor/src/main/java/ca/rmen/android/networkmonitor/app/email/Emailer.java
Thanks!
Aucun commentaire:
Enregistrer un commentaire