我目前正在编写一个简单的程序,通过gmail将电子邮件发送到Gmail帐户。 尝试过各种各样的方法,但我经常以同样的错误结束,“无法连接到SMTP主机:smtp.gmail.com,port:587;”
是否与属性设置有关。这是我的程序的片段。寻找解决方案:)
提前致谢
public static boolean SendMail(String from, String password, String message, String to[]){
String host = "smtp.gmail.com";
Properties prop = System.getProperties();
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.user", from);
prop.put("mail.smtp.password", password);
prop.put("mail.smtp.port", 587); //prop.put("mail.smtp.port", 465);//
prop.put("mail.smtp.auth", "true");
// check for the first value in the name of props or prop
Session session = Session.getDefaultInstance(prop, null);
MimeMessage mimemsg = new MimeMessage(session);
try{
mimemsg.setFrom(new InternetAddress(from));
// Get reciepents Address
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i=0;i<to.length;i++){
toAddress[i] = new InternetAddress(to[i]);
}
//Add all toAddress to mimemessage
for(int j=0;j<toAddress.length;j++){
mimemsg.addRecipient(RecipientType.TO, toAddress[j]);
}
// Add Subject.
mimemsg.setSubject(" MAIL from JAVA Program");
// Add Message to the content(input to the method )
mimemsg.setText(message);
Transport trans = session.getTransport("smtp");
trans.connect(host,from,password);
trans.sendMessage(mimemsg, mimemsg.getAllRecipients());
trans.close();
return true;
}catch(MessagingException me){
me.printStackTrace();
}
return false;
}
答案 0 :(得分:0)
使用此from
和password
进行身份验证,props.put("mail.smtp.port", "465");
465
端口号
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
也使用此属性:
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
答案 1 :(得分:0)
拥有props.put(“mail.smtp.host”,“173.194.78.108”);代替 props.put( “mail.smtp.host”, “smtp.gmail.com”);解决了这个问题
答案 2 :(得分:0)
您的设置似乎正确无误。 TLS的GMail SMTP端口为587。这看起来像是网络连接问题(主机名无法解析)。
telnet smtp.gmail.com 587
。你收到了SMTP问候语吗?