java.net.ConnectException从Java代码读取邮件附件期间

时间:2014-01-28 05:59:51

标签: java email javamail

我有一个Java代码来从邮件中读取邮件附件并将其存储在我的系统中的文件夹中。每次我从终端编译并运行代码时,我都会得到一个java.net.ConnectException:连接超时异常。

ReadMailSample.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;

public class ReadMailSample {
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
private String userName = "arindam@etranssolutions.com";// provide user name
private String password = "etrans1@";// provide password
String downloadDirectory = "/data/My Documents";

public ReadMailSample() {

}

public void readMails() {
    properties = new Properties();
    properties.setProperty("mail.host", "216.12.193.230");
    //properties.setProperty("mail.port", "995");
    properties.setProperty("mail.transport.protocol", "imaps");
    session = Session.getInstance(properties,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(userName, password);
                }
            });
    try {
        store = session.getStore("imaps");
        store.connect();
        inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        Message messages[] = inbox.search(new FlagTerm(
                new Flags(Flag.SEEN), false));
        ;
        System.out.println("Number of mails = " + messages.length);
        for (int i = 0; i < messages.length; i++) {
            Message message = messages[i];
            Address[] from = message.getFrom();
            System.out.println("-------------------------------");
            System.out.println("Date : " + message.getSentDate());
            System.out.println("From : " + from[0]);
            System.out.println("Subject: " + message.getSubject());
            System.out.println("Content :");
            processMessageBody(message);
            System.out.println("--------------------------------");

        }
        inbox.close(true);
        store.close();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

public void processMessageBody(Message message) {
    try {
        Object content = message.getContent();
        // check for string
        // then check for multipart
        if (content instanceof String) {
            System.out.println(content);
        } else if (content instanceof Multipart) {
            Multipart multiPart = (Multipart) content;
            procesMultiPart(multiPart);
        } else if (content instanceof InputStream) {
            InputStream inStream = (InputStream) content;
            int ch;
            while ((ch = inStream.read()) != -1) {
                System.out.write(ch);
            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

public void procesMultiPart(Multipart content) {

    try {

        for (int i = 0; i < content.getCount(); i++) {
            BodyPart bodyPart = content.getBodyPart(i);
            Object o;

            o = bodyPart.getContent();
            if (o instanceof String) {
                System.out.println("Text = " + o);
            } else if (null != bodyPart.getDisposition()
                    && bodyPart.getDisposition().equalsIgnoreCase(
                            Part.ATTACHMENT)) {
                String fileName = bodyPart.getFileName();
                System.out.println("fileName = " + fileName);
                InputStream inStream = bodyPart.getInputStream();
                FileOutputStream outStream = new FileOutputStream(new File(
                        downloadDirectory + fileName));
                byte[] tempBuffer = new byte[4096];// 4 KB
                int numRead;
                while ((numRead = inStream.read(tempBuffer)) != -1) {
                    outStream.write(tempBuffer);
                }
                inStream.close();
                outStream.close();
            }
            // else?

        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    ReadMailSample sample = new ReadMailSample();
    sample.readMails();
}
}

输出

root@arindam-pc:/home/arindam/Desktop/Random# javac -cp .:mail.jar ReadMailSample.java
root@arindam-pc:/home/arindam/Desktop/Random# java -cp .:mail.jar ReadMailSample
javax.mail.MessagingException: Connection timed out;
  nested exception is:
    java.net.ConnectException: Connection timed out
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:479)
    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 ReadMailSample.readMails(ReadMailSample.java:47)
    at ReadMailSample.main(ReadMailSample.java:141)
Caused by: java.net.ConnectException: Connection timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:570)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.iap.Protocol.<init>(Protocol.java:84)
    at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:87)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:446)
    ... 5 more

1 个答案:

答案 0 :(得分:0)

好的,谢谢大家......我得到了。我已将properties.setProperty(“mail.transport.protocol”,“imaps”)更改为properties.setProperty(“mail.transport.protocol”,“imap”)并将store = session.getStore(“imaps”)更改为store = session.getStore( “IMAP”)。

public void readMails() {
        properties = new Properties();
        properties.setProperty("mail.host", "mail.etranssolutions.com"); 
        //properties.setProperty("mail.port", "110");
        properties.setProperty("mail.transport.protocol", "imap");
        session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(userName, password);
                    }
                });
        try {
            store = session.getStore("imap");
            ...... (Rest Of the Code As it is ... )

输出

Number of mails = 0