当我未连接到办公网络时,以下用于读取gmail的代码可以正常工作
Properties props = new Properties();
props.setProperty("mail.imap.ssl.enable", "true");
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);
Store mailStore = mailSession.getStore("imap");
mailStore.connect("imap.gmail.com", "[email protected]", "pwd");
但是,当连接到办公室网络时,相同的代码不起作用。错误是:
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: closeFoldersOnStoreFailure
DEBUG IMAP: trying to connect to host "imap.gmail.com", port 993, isSSL true
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: imap.gmail.com, 993; timeout -1;
nested exception is:
java.net.UnknownHostException: imap.gmail.com
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
Caused by: java.net.UnknownHostException: imap.gmail.com
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:220)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
at java.base/java.net.Socket.connect(Socket.java:608)
at java.base/java.net.Socket.connect(Socket.java:557)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:359)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:134)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:131)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:763)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:698)
... 4 more
谷歌搜索后发现使用代理的建议。按照https://javaee.github.io/javamail/FAQ#proxy从JavaMail 1.6.0开始,我们可以设置代理详细信息属性。因此,将这些属性添加到代码中:
Properties props = new Properties();
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.protocol.proxy.host", "hostdetails");
props.setProperty("mail.protocol.proxy.port", "80");
//props.setProperty("mail.imap.socks.host", "hostdetails");
//props.setProperty("mail.imap.socks.port", "80");
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);
Store mailStore = mailSession.getStore("imap");
mailStore.connect("imap.gmail.com", "[email protected]", "pwd");
得到了同样的错误。尝试添加
props.setProperty("mail.imap.socks.host", "hostdetails");
,但出现相同的错误。任何想法如何使其工作? 最佳答案
正如@Bill Shannon所建议的,它在设置以下属性后可以工作
props.setProperty("mail.imap.proxy.host", "hostdetails");
props.setProperty("mail.imap.proxy.port", "portNumber");
您可以在上方看到我对Bill Shannon的评论。即使添加了以上两行,我最初还是有例外,然后我通过VPN连接到办公室n / w。一旦我去办公室进行测试,就可以使用这些代理设置了!现在,我再次使用VPN连接到办公室n / w,并且相同的代码运行正常!