JavaMail异常:无法连接到smtp主机

时间:2016-05-12 15:39:20

标签: java email javamail

我正在尝试使用java应用程序中的gmail发送电子邮件。但是我一直收到这个错误。

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

我希望有人可以帮我检查一下我的代码是否错误。我现在已经盯着它看了一段时间,我很困惑。谢谢!

我的邮寄代码

public void sendEmail(String email){
    String to=email;
    String from="user@gmail.com";
    String host="smtp.gmail.com";

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.socketFactory.port", String.valueOf(465));
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.port", "465");
    properties.put("mail.smtp.starttls.enabled", String.valueOf(true));
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    //Session session = Session.getDefaultInstance(properties);

    Session session= Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getpPasswordAuthentication(){
        return new  PasswordAuthentication("user@gmail.com", "password");
        }
    });

    try{
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));

        //set subject header field
        message.setSubject("Password reset");
        //set actual message
        message.setText("Your password has been reset");
        //send message
        Transport.send(message);
        System.out.println("Email has been sent");
    }catch(MessagingException mex){
        mex.printStackTrace();
    }

}

0 个答案:

没有答案