java中的电子邮件客户端

时间:2010-07-28 06:06:32

标签: java email client

试     {     属性props = new Properties();     props.put(“mail.smtp.starttls.enable”,“true”);     props.setProperty(“mail.transport.protocol”,“smtp”);     props.setProperty(“mail.smtp.host”,“smtp.gmail.com”);     props.put(“mail.smtp.auth”,“true”);     props.put(“mail.smtp.port”,“465”);     props.put(“mail.smtp.socketFactory.port”,“587”);     props.put(“mail.smtp.socketFactory.fallback”,“false”);     props.setProperty(“mail.user”,“username”);     props.setProperty(“mail.password”,“password”);

Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() 
  {
   protected PasswordAuthentication getPasswordAuthentication()
   { return new PasswordAuthentication("username","password"); }
  }); 
 session.setDebug(true);

 MimeMessage msg = new MimeMessage(session);

 InternetAddress addressFrom = new InternetAddress(from);
 msg.setFrom(addressFrom);

 msg.addRecipient(Message.RecipientType.TO,new InternetAddress(" Recipient mail id "));

 msg.setSubject(subject);
 Transport transport = session.getTransport();
 transport.connect();
 transport.sendMessage(msg,msg.getRecipients(Message.RecipientType.TO));
 transport.close();

} catch (Exception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}

我使用上面的代码将电子邮件发送到Gmail帐户。我在属性中设置了smtp主机值(smtp.gmail.com)和端口(465)。但电子邮件没有发送,我的应用程序卡住了很长时间。之后,我收到如下所示的错误

“javax.mail.MessagingException:无法连接到SMTP主机:smtp.gmail.com,port:465,响应:-1”

有谁能说出原因是什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

设置

props.put("mail.smtp.starttls.enable", "true");

启用端口 587 而不是465

的tls
props.put("mail.smtp.port", "587");

请参阅Google Doc

并检查你是否真的需要这些行

props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.fallback", "false");