Java Mail API:无法连接到主机

时间:2014-07-02 10:49:56

标签: java email javamail

我正在编写一个使用Java mail API发送电子邮件的程序,但每次它都显示异常Could not connect to host 'abc.xyz.pqr'。但是主机没有问题,因为我能够Telnet主机并且它已成功连接。

我正在尝试使用我的组织邮件服务器发送电子邮件。如果我使用gmail smtp,我的代码可以正常工作。我想代码属性可能存在一些问题。看看:

public void sendEMail(final EmailServiceRequest request, String filePath) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", EmailConstants.HOST);
    properties.put("mail.smtp.port", EmailConstants.PORT); 
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");

    //Session session = Session.getDefaultInstance(properties, null);
        Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(EmailConstants.USERNAME, EmailConstants.PASSWORD );
        }
    });

    // 2) compose message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(request.getSenderEmailId()));

        InternetAddress[] addressTo = new InternetAddress[request.getRecipients().size()]; 
        for (int i = 0; i < request.getRecipients().size(); i++) { 
          addressTo[i] = new InternetAddress(request.getRecipients().get(i)); 
        } 
        message.addRecipients(Message.RecipientType.TO, addressTo);

        message.setSubject(request.getSubject());

        // 3) create MimeBodyPart object and set your message text
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText(request.getContent());

        // 4) create new MimeBodyPart object and set DataHandler object to this object
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();


        DataSource source = new FileDataSource(filePath);

        messageBodyPart2.setDataHandler(new DataHandler(source));
        messageBodyPart2.setFileName(ApplicationUtils.getAttachmentName(filePath));

        // 5) create Multipart object and add MimeBodyPart objects to this object
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart1);
        multipart.addBodyPart(messageBodyPart2);

        // 6) set the multiplart object to the message object
        message.setContent(multipart);

        // 7) send message
     //Transport t = session.getTransport("smtp");
            try {
//                t.connect(EmailConstants.USERNAME, EmailConstants.PASSWORD);
//                t.sendMessage(message, message.getAllRecipients());
                Transport.send(message);
            } finally {
//                t.close();
            }
        System.out.println("message sent....");
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
}

我尝试了Transport.sendtransport.sendMessage方法,两者都给出了相同的异常。这是堆栈跟踪:

javax.mail.MessagingException: Could not connect to SMTP host: 

abc.xyz.pqr, port: 25;
  nested exception is:
    java.net.ConnectException: Operation timed out
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    at javax.mail.Service.connect(Service.java:297)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at com.pb.email.service.impl.EmailServiceImpl.sendEMail(EmailServiceImpl.java:104)
    at com.pb.scheduler.ScrapeReportScheduler.main(ScrapeReportScheduler.java:64)
Caused by: java.net.ConnectException: Operation timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:431)
    at java.net.Socket.connect(Socket.java:527)
    at java.net.Socket.connect(Socket.java:476)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
    ... 8 more

我不知道什么是错的?如果存在某些主机问题,为什么在命令提示符下使用telnet进行连接?我在代码中遗漏了什么吗?请帮忙。

PS:我理解应该从属性文件中读取USERNAMEPASSWORD。请忽略使用字符串文字的事实。

2 个答案:

答案 0 :(得分:1)

您的服务器可能正在侦听&#34; SMTP-over-SSL&#34;港口?尝试设置属性&#34; mail.smtp.ssl.enable&#34; to&#34; true&#34;。

另请参阅此common mistakes列表。

答案 1 :(得分:0)

我建议您使用SMTPTransport类。这是一个可以正常运作的课程。

    ...
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", EmailConstants.HOST);
    properties.put("mail.smtp.port", EmailConstants.PORT); //465
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

    Session session = Session.getInstance(properties, null);
    session.setDebug(true);
    try {
           MimeMessage message = new MimeMessage(session);
           message.setFrom(new InternetAddress(request.getSenderEmailId()));
           ...
           SMTPTransport t = (SMTPTransport)session.getTransport("smtp");
           t.connect(EmailConstants.USERNAME, EmailConstants.PASSWORD);
           t.sendMessage(msg, msg.getAllRecipients());
    }catch(Exception e){
           e.printStackTrace();
    }