我正在创建一个小应用程序来访问gmail并获取带附件的邮件。
Properties props = System.getProperties();
props.put("mail.user", login);
props.put("mail.host", pop3Host);
props.put("mail.debug", "false");
props.setProperty("mail.store.protocol", "imaps");
// set this session up to use SSL for IMAP connections
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// don't fallback to normal IMAP connections on failure.
props.setProperty("mail.imap.socketFactory.fallback", "false");
// use the simap port for imap/ssl connections.
props.setProperty("mail.imap.socketFactory.port", settings.getPop3Port().toString());
props.setProperty("mail.imap.partialfetch", "false");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", settings.getSmtpAuth().toString());
Session session=null;
session = Session.getInstance(props, new GMailAuthenticator(login, password));
Store store = null;
store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
SearchTerm st = new AndTerm(new SubjectTerm(subjectSubstringToSearch), unseenFlagTerm);
// Get some message references
Message [] messages = inbox.search(st);
System.out.println(messages.length + " -- Messages amount");
//Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
ArrayList<String> attachments = new ArrayList<String>();
LinkedList<MessageBean> listMessages = getPart(messages, attachments);
for(String s :attachments) {
System.out.println(s);
}
inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
BufferedReader reader = new BufferedReader (
new InputStreamReader(System.in));
for (int i=0, j=messages.length; i<j; i++) {
messages[i].setFlag(Flags.Flag.SEEN, true);
}
inbox.close(true);
store.close();
return listMessages;
}
private static LinkedList<MessageBean> getPart(Message[] messages, ArrayList<String> attachments) throws MessagingException, IOException {
LinkedList<MessageBean> listMessages = new LinkedList<MessageBean>();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Message inMessage : messages) {
attachments.clear();
if (inMessage.isMimeType("text/plain")) {
MessageBean message = new MessageBean(inMessage.getMessageNumber(), MimeUtility.decodeText(inMessage.getSubject()), inMessage.getFrom()[0].toString(), null, inMessage.getSentDate(), (String) inMessage.getContent(), false, null);
listMessages.add(message);
System.out.println("text/plain");
} else if (inMessage.isMimeType("multipart/*")) {
System.out.println("multipart");
Multipart mp = (Multipart) inMessage.getContent();
MessageBean message = null;
System.out.println(mp.getCount());
for (int i = 0; i < mp.getCount(); i++) {
Part part = mp.getBodyPart(i);
if ((part.getFileName() == null || part.getFileName() == "") && part.isMimeType("text/plain")) {
System.out.println(inMessage.getSentDate());
message = new MessageBean(inMessage.getMessageNumber(), inMessage.getSubject(), inMessage.getFrom()[0].toString(), null, inMessage.getSentDate(), (String) part.getContent(), false, null);
} else if (part.getFileName() != null || part.getFileName() != "") {
if ((part.getDisposition() != null) && (part.getDisposition().equals(Part.ATTACHMENT))) {
System.out.println(part.getFileName());
attachments.add(saveFile(MimeUtility.decodeText(part.getFileName()), part.getInputStream()));
if (message != null) {
message.setAttachments(attachments);
}
}
}
}
listMessages.add(message);
}
}
return listMessages;
}
//method for saving attachment on local disk
private static String saveFile(String filename, InputStream input) {
String strDirectory = "D:\\temp\\attachments";
try{
// Create one directory
boolean success = (new File(strDirectory)).mkdir();
if (success) {
System.out.println("Directory: "
+ strDirectory + " created");
}
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
String path = strDirectory+"\\" + filename;
try {
byte[] attachment = new byte[input.available()];
input.read(attachment);
File file = new File(path);
FileOutputStream out = new FileOutputStream(file);
out.write(attachment);
input.close();
out.close();
return path;
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
}
MessageBean :
public class MessageBean implements Serializable {
private String subject;
private String from;
private String to;
private Date dateSent;
private String content;
private boolean isNew;
private int msgId;
private ArrayList<String> attachments;
public MessageBean(int msgId, String subject, String from, String to, Date dateSent, String content, boolean isNew, ArrayList<String> attachments) {
this.subject = subject;
this.from = from;
this.to = to;
this.dateSent = dateSent;
this.content = content;
this.isNew = isNew;
this.msgId = msgId;
this.attachments = attachments;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public Date getDateSent() {
return dateSent;
}
public void setDateSent(Date dateSent) {
this.dateSent = dateSent;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean aNew) {
isNew = aNew;
}
public int getMsgId() {
return msgId;
}
public void setMsgId(int msgId) {
this.msgId = msgId;
}
public ArrayList<String> getAttachments() {
return attachments;
}
public void setAttachments(ArrayList<String> attachments) {
this.attachments = new ArrayList<String>(attachments);
}
}
我可以连接到我的邮件帐户并查看大量未看到的邮件,但似乎MessageBean
没有填充附件。
最大的问题是我在没有互联网连接的计算机上开发我的应用程序。所以我构建jar,转到具有inet的计算机,java -jar
并注视NullPointer异常。我无法调试这个垃圾。请有人,请发现我的错误在哪里。
修改 此代码适用于 gmail pop ,显然还有其他连接。
答案 0 :(得分:0)
因为当你从中获取元素时你的列表为null,所以你可以在Message Bean中创建新的ArrayList对象,然后复制元素
private List<String> attachments= new ArrayList<String>();
public MessageBean(int msgId, String subject, String from, String to, Date dateSent, String content, boolean isNew, ArrayList<String> attachments) {
this.subject = subject;
this.from = from;
this.to = to;
this.dateSent = dateSent;
this.content = content;
this.isNew = isNew;
this.msgId = msgId;
this.attachments.addAll(attachments);
}
答案 1 :(得分:0)
JavaMail常见问题解答包括debugging tips以及tips for using Gmail。
你对pop3host有什么价值?希望它是“imap.gmail.com”而不是“pop.gmail.com”。
请注意,您可以删除所有这些套接字工厂属性,但不需要它们。
答案 2 :(得分:0)
-fav
答案 3 :(得分:0)
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
public class MailProcessor implements Runnable {
String downloadDirectory = "C:/tmp/downloads/";
private Message message;
public MailProcessor() {
}
public void run() {
System.out.println("Starting processing a message with thread id"
+ Thread.currentThread().getId());
try {
readMails();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Finished processing a message with thread id"
+ Thread.currentThread().getId());
}
public void readMails() throws MessagingException {
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("--------------------------------");
}
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) {
InputStream inStream = null;
FileOutputStream outStream = null;
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);
inStream = bodyPart.getInputStream();
outStream = new FileOutputStream(new File(downloadDirectory
+ fileName));
byte[] tempBuffer = new byte[4096];// KB
int numRead = 0;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
}
// else?
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
//
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public MailProcessor setMessage(Message message) {
this.message = message;
return this;
}
}
===========================================================================
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.mail.Message;
public class MailServer {
public static void start(int threadCount,
int frequencyInSecondsToListenMail) {
long lastFinished = System.currentTimeMillis();
do {
if ((System.currentTimeMillis() - lastFinished) / 1000 >= frequencyInSecondsToListenMail) {
readMails(threadCount);
}
} while (true);
}
private static void readMails(int threadCount) {
List<Message> recentMessages = MailUtility.readMessages();
ExecutorService executorService = Executors
.newFixedThreadPool(threadCount);
if(recentMessages == null || recentMessages.isEmpty()){
System.out.println("No messages found.");
}
for (Message message : recentMessages) {
executorService
.execute(new MailProcessor().setMessage(message));
}
executorService.shutdown();
}
public static void main(String[] args) {
MailServer.start(2, 2);
}
}
=======================================================================
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
public final class MailUtility {
public static List<Message> readMessages() {
Properties properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "");
properties.setProperty("mail.transport.protocol", "imaps");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
final Properties mailServerProperties = PropertyFileReader
.getProperties("mail-server.properties");
String username = mailServerProperties
.getProperty("username");
String password = mailServerProperties
.getProperty("password");
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Store store;
try {
store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
List<Message> result = new ArrayList<Message>();
for(Message message : messages){
result.add(new MimeMessage((MimeMessage)message));
}
inbox.close(false);
store.close();
return result;
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
==========================================================================
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Flags.Flag;
public class MessagesProcessor implements Runnable {
String downloadDirectory = "C:/tmp/downloads/";
private List<Message> messages;
public MessagesProcessor() {
}
public void run() {
System.out.println("Starting processing " + messages.size()
+ " messages in the thread " + Thread.currentThread().getId());
try {
readMails();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Finished processing " + messages.size()
+ " messages in the thread " + Thread.currentThread().getId());
}
public void readMails() throws MessagingException {
for (Message message : messages) {
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("--------------------------------");
message.setFlag(Flag.SEEN, true);
}
}
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) {
InputStream inStream = null;
FileOutputStream outStream = null;
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);
inStream = bodyPart.getInputStream();
outStream = new FileOutputStream(new File(downloadDirectory
+ fileName));
byte[] tempBuffer = new byte[4096];// KB
int numRead;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
}
// else?
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
//
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public MessagesProcessor setMessages(List<Message> messages) {
this.messages = messages;
return this;
}
}
============================================================================
import java.io.IOException;
import java.util.Properties;
public final class PropertyFileReader {
public static Properties getProperties(String filename) {
ClassLoader contextClassLoader = Thread.currentThread()
.getContextClassLoader();
Properties properties = new Properties();
try {
properties.load(contextClassLoader.getResourceAsStream(filename));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return properties;
}
}
答案 4 :(得分:0)
for(int i=0; i < timeToExecute; i++){
for(int j=0;j<5;j++){
Runnable runner = null;
if(i+1 == timeToExecute){
endIndex = count;
runner = new TaskPrint(startIndex, endIndex, inbox);
} else {
runner = new TaskPrint(startIndex, endIndex, inbox);
}
executor.execute(runner);
startIndex = endIndex + 1;
endIndex = endIndex + 200;
i++;
}
}
答案 5 :(得分:0)
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class DAOUtils {
public static void createTable(){
String createSql = "CREATE TABLE MAILBOX " +
" from VARCHAR(255), " +
" sentDate VARCHAR(255), " +
" subject VARCHAR(255), " +
" message VARCHAR(255)";
Connection con = DBConnection.getInstance().getConnection();
Statement stmt;
try {
stmt = con.createStatement();
stmt.executeUpdate(createSql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void insertRow(MailInfo mes){
Connection conn = DBConnection.getInstance().getConnection();
String sql = "INSERT INTO MAILBOX (from, sentDate, subject, message)" +
"VALUES (?, ?, ?, ?)";
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, mes.getFrom());
preparedStatement.setString(2, mes.getSentDate());
preparedStatement.setString(3, mes.getSubject());
preparedStatement.setString(4, mes.getMessageContent());
preparedStatement.executeUpdate();
} catch (SQLException e){
e.printStackTrace();
}
}
}
===========================================================================
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBConnection {
private static Connection connect;
private static DBConnection instance;
private DBConnection()
{
final Properties mailServerProperties = PropertyFileReader
.getProperties("mail-server.properties");
String username = mailServerProperties
.getProperty("db_username");
String password = mailServerProperties
.getProperty("db_password");
String ip = mailServerProperties
.getProperty("ip");
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://" +ip +"/database",username,password);
}catch(SQLException e)
{
System.err.println(e.getMessage());
}catch(ClassNotFoundException e)
{
System.err.println(e.getMessage());
}
}
public static DBConnection getInstance()
{
if(instance == null) {
instance = new DBConnection();
}
return instance;
}
public static Connection getConnection(){
return connect;
}
}
=========================================================================
public class MailInfo {
private String sentDate;
private String subject;
private String from;
private String messageContent;
public String getSentDate() {
return sentDate;
}
public void setSentDate(String sentDate) {
this.sentDate = sentDate;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getMessageContent() {
return messageContent;
}
public void setMessageContent(String messageContent) {
this.messageContent = messageContent;
}
}
===========================================================================
mail-server.properties
username = hhh60
password = $test123$
db_username = root
db_password = root
ip = localhost:3305
use_db = false
==========================================================================
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.mail.Message;
public class MailServer {
public static void start(int messageCountForEachThread, int threadCount) {
List<Message> messages = MailUtility.readMessages();
int messageLength = messages.size();
if (messages == null || messages.size() == 0) {
System.out.println("No messages found");
return;
}
System.out.println("Number of messages found " + messageLength);
if (messageLength <= messageCountForEachThread) {
new Thread(new MessagesProcessor().setMessages(messages)).start();
} else {
ExecutorService executorService = Executors
.newFixedThreadPool(threadCount);
int x = messageLength / messageCountForEachThread;
int remaining = messageLength % messageCountForEachThread;
int i = 1;
while (i <= x) {
int startIndex = (i - 1) * messageCountForEachThread;
int endIndex = startIndex + messageCountForEachThread;
List<Message> messagesForEachThread = messages.subList(
startIndex, endIndex);
executorService.execute(new MessagesProcessor()
.setMessages(messagesForEachThread));
i++;
}
int startIndex = i - 1 * messageCountForEachThread;
int endIndex = startIndex + remaining;
List<Message> messagesForEachThread = messages.subList(startIndex,
endIndex);
executorService.execute(new MessagesProcessor()
.setMessages(messagesForEachThread));
executorService.shutdown();
}
}
public static void main(String[] args) {
MailServer.start(2, 2);
}
}
=======================================================================
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public final class MailUtility {
public static List<Message> readMessages() {
final Properties mailServerProperties = PropertyFileReader
.getProperties("mail-server.properties");
boolean useDb = Boolean.parseBoolean(mailServerProperties.getProperty("use_db"));
Properties properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "");
properties.setProperty("mail.transport.protocol", "imaps");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
String username = mailServerProperties
.getProperty("username");
String password = mailServerProperties
.getProperty("password");
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Store store;
try {
store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
if(useDb){
DAOUtils.createTable();
}
return Arrays.asList(messages);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
================================================================
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
public class MessagesProcessor implements Runnable {
String downloadDirectory = "C:/tmp/downloads/";
boolean useDb;
private List<Message> messages;
public MessagesProcessor() {
final Properties mailServerProperties = PropertyFileReader
.getProperties("mail-server.properties");
useDb = Boolean.parseBoolean(mailServerProperties.getProperty("use_db"));
}
public void run() {
System.out.println("Starting processing " + messages.size()
+ " messages in the thread " + Thread.currentThread().getId());
try {
readMails();
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("Finished processing " + messages.size()
+ " messages in the thread " + Thread.currentThread().getId());
}
public void readMails() throws MessagingException {
for (Message message : messages) {
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("--------------------------------");
if(useDb){
MailInfo info = new MailInfo();
info.setFrom(from[0].toString());
info.setSentDate(message.getSentDate().toString());
info.setSubject(message.getSubject());
info.setMessageContent(message.toString());
DAOUtils.insertRow(info);
}
}
}
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) {
InputStream inStream = null;
FileOutputStream outStream = null;
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);
inStream = bodyPart.getInputStream();
File f = new File(downloadDirectory + fileName);
if(!f.exists()){
System.out.println("Downloading file : " + fileName + " .............");
outStream = new FileOutputStream(f);
byte[] tempBuffer = new byte[4096];// KB
int numRead = 0;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
System.out.println("Download completed");
} else {
System.out.println("Given file name already exists");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
//
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public MessagesProcessor setMessages(List<Message> messages) {
this.messages = messages;
return this;
}
}
==================================================================
import java.io.IOException;
import java.util.Properties;
public final class PropertyFileReader {
public static Properties getProperties(String filename) {
ClassLoader contextClassLoader = Thread.currentThread()
.getContextClassLoader();
Properties properties = new Properties();
try {
properties.load(contextClassLoader.getResourceAsStream(filename));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return properties;
}
}
答案 6 :(得分:0)
package Test.TestArtifact;
import java.time.LocalDate;
import java.util.Date;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeBodyPart;
public class TaskPrint implements Runnable{
private Message messages;
private Date startDate;
public TaskPrint(Date startDate, Message messages){
this.startDate = startDate;
this.messages = messages;
}
public void run() {
try {
if(messages.getSentDate().after(startDate) && messages.getSentDate().before(startDate)){
Address[] in = messages.getFrom();
String contentType = messages.getContentType();
String messageContent = "";
String attachFiles = "";
if(contentType.contains("multiport")){
Multipart multipart = (Multipart) messages.getContent();
int noOfParts = multipart.getCount();
for(int partCount =0; partCount < noOfParts; partCount++){
MimeBodyPart mime = (MimeBodyPart) multipart.getBodyPart(partCount);
if(Part.ATTACHMENT.equalsIgnoreCase(mime.getDisposition())){
String fileName = mime.getFileName();
attachFiles += fileName + ",";
if(fileName.endsWith("=")){
mime.saveFile("C:\\tmp\\downloads" + fileName);
} else {
messageContent = mime.getContent().toString();
}
}
if(attachFiles.length() > 1){
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
} else if(contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = messages.getContent();
if(content != null){
messageContent = content.toString();
}
}
}
}
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
答案 7 :(得分:0)
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblAngle = new System.Windows.Forms.Label();
this.trckBarAngle = new System.Windows.Forms.TrackBar();
this.btnFire = new System.Windows.Forms.Button();
this.btnRedraw = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.trckBarAngle)).BeginInit();
this.SuspendLayout();
//
// lblAngle
//
this.lblAngle.AutoSize = true;
this.lblAngle.Location = new System.Drawing.Point(13, 13);
this.lblAngle.Name = "lblAngle";
this.lblAngle.Size = new System.Drawing.Size(46, 17);
this.lblAngle.TabIndex = 0;
this.lblAngle.Text = "label1";
//
// trckBarAngle
//
this.trckBarAngle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.trckBarAngle.LargeChange = 10;
this.trckBarAngle.Location = new System.Drawing.Point(732, 42);
this.trckBarAngle.Maximum = 360;
this.trckBarAngle.Minimum = -360;
this.trckBarAngle.Name = "trckBarAngle";
this.trckBarAngle.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trckBarAngle.Size = new System.Drawing.Size(56, 495);
this.trckBarAngle.TabIndex = 1;
this.trckBarAngle.Scroll += new System.EventHandler(this.trckBarAngle_Scroll);
//
// btnFire
//
this.btnFire.Location = new System.Drawing.Point(632, 13);
this.btnFire.Name = "btnFire";
this.btnFire.Size = new System.Drawing.Size(75, 23);
this.btnFire.TabIndex = 2;
this.btnFire.Text = "Fire";
this.btnFire.UseVisualStyleBackColor = true;
this.btnFire.Click += new System.EventHandler(this.btnFire_Click);
//
// btnRedraw
//
this.btnRedraw.Location = new System.Drawing.Point(713, 13);
this.btnRedraw.Name = "btnRedraw";
this.btnRedraw.Size = new System.Drawing.Size(75, 23);
this.btnRedraw.TabIndex = 2;
this.btnRedraw.Text = "Redraw";
this.btnRedraw.UseVisualStyleBackColor = true;
this.btnRedraw.Click += new System.EventHandler(this.btnRedraw_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 549);
this.Controls.Add(this.btnRedraw);
this.Controls.Add(this.btnFire);
this.Controls.Add(this.trckBarAngle);
this.Controls.Add(this.lblAngle);
this.Name = "Form1";
this.Text = "Form1";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.LineDrawEvent);
((System.ComponentModel.ISupportInitialize)(this.trckBarAngle)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblAngle;
private System.Windows.Forms.TrackBar trckBarAngle;
private System.Windows.Forms.Button btnFire;
private System.Windows.Forms.Button btnRedraw;
}
答案 8 :(得分:0)
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
public class ExecutorServiceExample {
public static void main(String[] args) throws MessagingException {
ExecutorServiceExample eService = new ExecutorServiceExample();
Folder inbox = eService.getInboxFolder();
Message[] messages = inbox.getMessages();
System.out.println("Total Mail count = " + messages.length);
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
for(Message message: messages){
Runnable runner = new TaskPrint(message);
executor.execute(runner);
}
System.out.println("Maximum threads inside pool " + executor.getMaximumPoolSize());
executor.shutdown();
try {
Thread.sleep(1000);
executor.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private Folder getInboxFolder() throws MessagingException{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props,null);
Store store = session.getStore();
store.connect("imap.gmail.com", "aaa@gmail.com", "aaaaa");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
return inbox;
}
}
答案 9 :(得分:0)
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
public class TaskPrint implements Runnable{
private Message message;
public TaskPrint(Message message){
this.message = message;
}
public void run() {
try {
Multipart multipart = (Multipart) message.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
bodyPart.getFileName() != null) {
continue; // dealing with attachments only
}
System.out.println("Message subject " + message.getSubject());
InputStream is = bodyPart.getInputStream();
File f = new File("c:/tmp/" + bodyPart.getFileName());
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[4096];
int bytesRead;
while((bytesRead = is.read(buf))!=-1) {
fos.write(buf, 0, bytesRead);
}
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch(MessagingException e){
e.printStackTrace();
}
}
}