Java 从独立应用程序轮询 GMail 收件箱接收邮件的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23424003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Right way to poll GMail inbox for incoming mail from stand-alone application
提问by Tapas Bose
I am trying to poll GMail inbox for incoming mail. Here is what I have:
我正在尝试轮询 GMail 收件箱以获取收到的邮件。这是我所拥有的:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
public class GmailIncomingTest {
public static void main(String[] args) {
try {
String username = "[email protected]";
String password = "mypassword";
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
IMAPStore store = (IMAPStore) session.getStore("imaps");
store.connect("smtp.gmail.com", username, password);
IMAPFolder inbox = (IMAPFolder) store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
inbox.addMessageCountListener(new MessageCountListener() {
@Override
public void messagesRemoved(MessageCountEvent event) {
}
@Override
public void messagesAdded(MessageCountEvent event) {
Message[] messages = event.getMessages();
for (Message message : messages) {
try {
System.out.println("Mail Subject:- " + message.getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
});
new Thread(new Runnable() {
private static final long KEEP_ALIVE_FREQ = 10000;
@Override
public void run() {
while (!Thread.interrupted()) {
try {
inbox.idle();
Thread.sleep(KEEP_ALIVE_FREQ);
} catch (InterruptedException e) {
} catch (MessagingException e) {
}
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I would like to know if this is a right way to do this or if there is any other better way.
我想知道这是否是正确的方法,或者是否有其他更好的方法。
采纳答案by salyh
As long your server supports IDLE (gmail will) and you want only notified about new mails (since programm is running) than the below programm should fit your needs. If server does not support IDLE and/or older message are relevant (or other events like folder rename etc) then you need to modify the code. Have a look here for some hints: https://github.com/salyh/elasticsearch-imap/blob/master/src/main/java/de/saly/elasticsearch/importer/imap/mailsource/ParallelPollingIMAPMailSource.java
只要您的服务器支持空闲(gmail 将)并且您只想通知有关新邮件的通知(因为程序正在运行),那么下面的程序应该适合您的需要。如果服务器不支持 IDLE 和/或旧消息相关(或其他事件,如文件夹重命名等),则您需要修改代码。看看这里的一些提示:https: //github.com/salyh/elasticsearch-imap/blob/master/src/main/java/de/saly/elasticsearch/importer/imap/mailsource/ParallelPollingIMAPMailSource.java
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
public class GmailIncomingTest {
private static final String username = "[email protected]";
private static final String password = "passwd";
public static void main(String[] args) {
Properties properties = new Properties();
// properties.put("mail.debug", "true");
properties.put("mail.store.protocol", "imaps");
properties.put("mail.imaps.host", "imap.gmail.com");
properties.put("mail.imaps.port", "993");
properties.put("mail.imaps.timeout", "10000");
Session session = Session.getInstance(properties); // not
// getDefaultInstance
IMAPStore store = null;
Folder inbox = null;
try {
store = (IMAPStore) session.getStore("imaps");
store.connect(username, password);
if (!store.hasCapability("IDLE")) {
throw new RuntimeException("IDLE not supported");
}
inbox = (IMAPFolder) store.getFolder("INBOX");
inbox.addMessageCountListener(new MessageCountAdapter() {
@Override
public void messagesAdded(MessageCountEvent event) {
Message[] messages = event.getMessages();
for (Message message : messages) {
try {
System.out.println("Mail Subject:- " + message.getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
});
IdleThread idleThread = new IdleThread(inbox);
idleThread.setDaemon(false);
idleThread.start();
idleThread.join();
// idleThread.kill(); //to terminate from another thread
} catch (Exception e) {
e.printStackTrace();
} finally {
close(inbox);
close(store);
}
}
private static class IdleThread extends Thread {
private final Folder folder;
private volatile boolean running = true;
public IdleThread(Folder folder) {
super();
this.folder = folder;
}
public synchronized void kill() {
if (!running)
return;
this.running = false;
}
@Override
public void run() {
while (running) {
try {
ensureOpen(folder);
System.out.println("enter idle");
((IMAPFolder) folder).idle();
} catch (Exception e) {
// something went wrong
// wait and try again
e.printStackTrace();
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// ignore
}
}
}
}
}
public static void close(final Folder folder) {
try {
if (folder != null && folder.isOpen()) {
folder.close(false);
}
} catch (final Exception e) {
// ignore
}
}
public static void close(final Store store) {
try {
if (store != null && store.isConnected()) {
store.close();
}
} catch (final Exception e) {
// ignore
}
}
public static void ensureOpen(final Folder folder) throws MessagingException {
if (folder != null) {
Store store = folder.getStore();
if (store != null && !store.isConnected()) {
store.connect(username, password);
}
} else {
throw new MessagingException("Unable to open a null folder");
}
if (folder.exists() && !folder.isOpen() && (folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
System.out.println("open folder " + folder.getFullName());
folder.open(Folder.READ_ONLY);
if (!folder.isOpen())
throw new MessagingException("Unable to open folder " + folder.getFullName());
}
}
}
回答by Bill Shannon
You might want to fix these common mistakes, and you need to connect to the imap server, not the smtp server (see the GMail example in the JavaMail FAQ). Otherwise, you've got the right general idea. You might want to look at the monitor.java sample program.
您可能想要修复这些常见错误,并且需要连接到 imap 服务器,而不是 smtp 服务器(请参阅JavaMail FAQ 中的GMail 示例)。否则,你就有了正确的总体思路。您可能想查看monitor.java 示例程序。
You probably also want to handle more error cases when the connection drops while you're using it.
您可能还想在使用它时连接断开时处理更多错误情况。