JavaMail无法发送电子邮件

时间:2014-07-03 00:19:41

标签: java gmail javamail

我正在尝试在java中编写一个将发送电子邮件的应用程序,我在youtube上找到了一个教程并试图遵循它。但它仍然不适合我,这是我得到的错误

Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25, response: 421
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1949)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at libraryFineList.ParseRecords.main(ParseRecords.java:90)

我不知道,有什么不对,我在谷歌找到的任何东西都无济于事,

这是代码

    public static void main(String[] args) throws IOException, MessagingException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", 465);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, 
            new javax.mail.Authenticator(){
        protected  PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication("user@gmail.com", "pass");

        }
    }

            );

    try{
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("user@gmail.com"));
        message.addRecipient(Message.RecipientType.TO,
                   new InternetAddress("ycharnetskaya@gmail.com", "Mr. User"));
        message.setSubject("Your Example.com account has been activated");
        message.setText("Worked");
  Transport.send(message);
    }catch(Exception e){
        e.printStackTrace();
    }

here are the libraries that i downloaded and added to build path

enter image description here

2 个答案:

答案 0 :(得分:2)

您遵循的教程充满了错误。首先修复这些common mistakes。然后按照instructions for connecting to Gmail进行操作。如果您仍然遇到问题,可以在JavaMail FAQ找到更多帮助。还有很多sample programs可用。

答案 1 :(得分:0)

奇怪的是,您的错误消息抱怨连接到localhost时出现问题:25当您的属性文件清楚地表明您应该使用smtp.gmail.com时。

我认为你的主机文件没有任何狡猾的东西,它将smtp.gmail.com重定向回127.0.0.1或者什么,是吗?如果您从命令行ping smtp.gmail.com会发生什么?

除此之外,我建议您检查是否使用了最新版本的Java Mail。