📄 emaillistener.java
字号:
/**
* $RCSfile$
* $Revision: $
* $Date: $
*
* Copyright (C) 2008 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution, or a commercial license
* agreement with Jive.
*/
package org.jivesoftware.openfire.plugin.emailListener;
import com.sun.mail.imap.IMAPFolder;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils;
import org.xmpp.packet.JID;
import javax.mail.*;
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import java.util.Collection;
import java.util.ArrayList;
/**
* Email listener service that will send an instant message to specified users
* when new email messages are found.
*
* @author Gaston Dombiak
*/
public class EmailListener {
private static final String SSL_FACTORY = "org.jivesoftware.util.SimpleSSLSocketFactory";
private static final EmailListener instance = new EmailListener();
/**
* Message listener that will process new emails found in the IMAP server.
*/
private MessageCountAdapter messageListener;
private Folder folder;
private boolean started = false;
public static EmailListener getInstance() {
return instance;
}
private EmailListener() {
}
/**
* Returns true if a connection to the IMAP server was successful.
*
* @param host Host to connect to.
* @param port Port to connect over.
* @param isSSLEnabled True if an SSL connection will be attempted.
* @param user Username to use for authentication.
* @param password Password to use for authentication.
* @param folderName Folder to check.
* @return true if a connection to the IMAP server was successful.
*/
public static boolean testConnection(String host, int port, boolean isSSLEnabled, String user, String password,
String folderName) {
Folder folder = openFolder(host, port, isSSLEnabled, user, password, folderName);
boolean success = folder != null && folder.isOpen();
closeFolder(folder, null);
return success;
}
/**
* Opens a connection to the IMAP server and listen for new messages.
*/
public void start() {
// Check that the listner service is not running
if (started) {
return;
}
Thread thread = new Thread("Email Listener Thread") {
public void run() {
// Open the email folder and keep it
folder = openFolder(getHost(), getPort(), isSSLEnabled(), getUser(), getPassword(), getFolder());
if (folder != null) {
// Listen for new email messages until #stop is requested
listenMessages();
}
}
};
thread.setDaemon(true);
thread.start();
started = true;
}
/**
* Closes the active connection to the IMAP server.
*/
public void stop() {
closeFolder(folder, messageListener);
started = false;
folder = null;
messageListener = null;
}
private void listenMessages() {
try {
// Add messageCountListener to listen for new messages
messageListener = new MessageCountAdapter() {
public void messagesAdded(MessageCountEvent ev) {
Message[] msgs = ev.getMessages();
// Send new messages to specified users
for (Message msg : msgs) {
try {
sendMessage(msg);
}
catch (Exception e) {
Log.error("Error while sending new email message", e);
}
}
}
};
folder.addMessageCountListener(messageListener);
// Check mail once in "freq" MILLIseconds
int freq = getFrequency();
boolean supportsIdle = false;
try {
if (folder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) folder;
f.idle();
supportsIdle = true;
}
}
catch (FolderClosedException fex) {
throw fex;
}
catch (MessagingException mex) {
supportsIdle = false;
}
while (messageListener != null) {
if (supportsIdle && folder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) folder;
f.idle();
}
else {
Thread.sleep(freq); // sleep for freq milliseconds
// This is to force the IMAP server to send us
// EXISTS notifications.
if (folder != null && folder.isOpen()) {
folder.getMessageCount();
}
}
}
}
catch (Exception ex) {
Log.error("Error listening new email messages", ex);
}
}
private void sendMessage(Message message) throws Exception {
StringBuilder sb = new StringBuilder();
sb.append("New email has been received\n");
// FROM
sb.append("From: ");
for (Address address : message.getFrom()) {
sb.append(address.toString()).append(" ");
}
sb.append("\n");
// DATE
Date date = message.getSentDate();
sb.append("Received: ").append(date != null ? date.toString() : "UNKNOWN").append("\n");
// SUBJECT
sb.append("Subject: ").append(message.getSubject()).append("\n");
// Apend body
appendMessagePart(message, sb);
// Send notifications to specified users
for (String user : getUsers()) {
// Create notification message
org.xmpp.packet.Message notification = new org.xmpp.packet.Message();
notification.setFrom(XMPPServer.getInstance().getServerInfo().getXMPPDomain());
notification.setTo(user);
notification.setSubject("New email has been received");
notification.setBody(sb.toString());
// Send notification message
XMPPServer.getInstance().getMessageRouter().route(notification);
}
}
private void appendMessagePart(Part part, StringBuilder sb) throws Exception {
/*
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
*/
if (part.isMimeType("text/plain")) {
// This is plain text"
sb.append((String) part.getContent()).append("\n");
}
else if (part.isMimeType("multipart/*")) {
// This is a Multipart
Multipart mp = (Multipart) part.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++) {
appendMessagePart(mp.getBodyPart(i), sb);
}
}
else if (part.isMimeType("message/rfc822")) {
// This is a Nested Message
appendMessagePart((Part) part.getContent(), sb);
}
else {
/*
* If we actually want to see the data, and it's not a
* MIME type we know, fetch it and check its Java type.
*/
/*Object o = part.getContent();
if (o instanceof String) {
// This is a string
System.out.println((String) o);
}
else if (o instanceof InputStream) {
// This is just an input stream
InputStream is = (InputStream) o;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -