我試圖使用Gmail SMTP向任何Gmail帳戶發送簡單的電子郵件。得到下面的錯誤。使用Gmail中的Gmail帳戶發送郵件
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection timed out: connect
我的代碼是
package common;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPMessage;
public class SimpleMail{
/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for SSL: 465
*/
public static void main(String[] args) {
String to="[email protected]";
String subject="New Mail";
String msg="test test";
final String user="gmailuser";
final String pass="gmailpassowd";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587"); //this is optional
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,pass);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(subject);
message.setText(msg);
Transport.send(message);
System.out.println("Mail sent..");
}catch(Exception e)
{
System.out.println(e);
}
}
}
是您的Internet連接是否正常工作?你在使用一些代理嗎? – Aakash
我認爲你應該從http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/通過SSL例子來試用Gmail。此外,您的收件人的電子郵件地址(如果其Gmail)應該有此設置,否則郵件不會發送 - 「Gmail安全設置 - >帳戶權限 - >訪問安全性較低的應用程序」 – LittlePanda
java.net.ConnectException:連接超時:連接意味着你有一些互聯網和/或防火牆問題 – Dev