我想从gmail下载来自esb端的特定电子邮件ID的电子邮件附件(此处为图片),我查看了https://javaee.github.io/javamail/docs/api/javax/mail/search/MessageIDTerm.html和https://javaee.github.io/javamail/docs/api/javax/mail/search/SearchTerm.html,但没有得到特定附件电子邮件MessageId。
对于其他一些检查,例如unreadsearchterm
,subjectTerm
,下载过程成功。但是使用MessageIdTerm
的方法并不成功。下载后,我将该附件移动到其他名称的其他文件夹中(下载时,我无法更改附件名称,因此请在此处使用一些临时文件夹)。注意:ESB像messageID
一样返回16cb0e2c30c18f11
,id
仅是正确的,因为它显示正确的电子邮件,而在.*/inbox/{emailmessageid}
之后直接在URL中进行搜索。但是,如果我打开标题,它会显示其他id
,例如ece641efe83480e9bf34c31738eea59e@www.something.com
打包com.qrs.in;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.search.AndTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.MessageIDTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.sun.xml.internal.org.jvnet.mimepull.MIMEMessage;
public class EmailAttachmentReceiver {
private static String saveDirectory;
static String sftp_path=null;
/*To set LocalDirectory*/
public static void setSaveDirectory(String dir) {
saveDirectory = dir;
}
/*Setting Properties*/
private static Properties getServerProperties(String protocol, String host, String port) {
Properties properties = new Properties();
// server setting
properties.put(String.format("mail.%s.host", protocol), host);
properties.put(String.format("mail.%s.port", protocol), port);
// SSL setting
properties.setProperty(String.format("mail.%s.socketFactory.class", protocol),
"javax.net.ssl.SSLSocketFactory");
properties.setProperty(String.format("mail.%s.socketFactory.fallback", protocol), "false");
properties.setProperty(String.format("mail.%s.socketFactory.port", protocol), String.valueOf(port));
return properties;
}
/*File Movement and Delete Process*/
public static void moveFile(String tempDirectory,String fileName,String saveDirectory,String transactionID)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String fileExtension=fileName.substring(fileName.lastIndexOf("."));
File file = new File(tempDirectory+File.separator+fileName);
if(file.renameTo
(new File(saveDirectory+File.separator+transactionID+"_"+dateFormat.format(new Date())+fileExtension)))
/*(new File(saveDirectory+File.separator+emailmessageID))) */
{
// if file copied successfully then delete the original file
file.delete();
System.out.println("File moved successfully");
}
else
{
System.out.println("Failed to move the file");
}
}
/*Downloading EmailAttachment into localfolder*/
public static void downloadEmailAttachments(String protocol, String host, String port, String userName, String password,
String tempDirectory,String saveDirectory,String transactionID,String emailmessageID) throws MessagingException{
System.out.println("===Inside downloadEmailAttachments Process====");
Properties properties = getServerProperties(protocol, host, port);
Session session = Session.getDefaultInstance(properties);
int status = 0;
try {
Store store = session.getStore(protocol);
store.connect(userName, password);
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
System.out.println("No of Unread Messages : " + folderInbox.getUnreadMessageCount());
// (3) create a search term for all "unseen" messages
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
//String emailsubjectregex="Sell My Car.*";
//Message[] arrayMessages = folderInbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
//already tried, it is success.
SearchTerm searchTerm = new AndTerm(new SubjectTerm("Sell My Car - von Bibra Group"), unseenFlagTerm);
//Newly Tried,here is the problem
SearchTerm searchTerm = new AndTerm(new MessageIDTerm(emailmessageID), unseenFlagTerm);
Message[] arrayMessages = null;
arrayMessages = folderInbox.search(searchTerm);
for (int i = 0; i < arrayMessages.length; i++) {
// for (int i = 0; i < 1; i++) {
Message message = arrayMessages[i];
Address[] fromAddress = message.getFrom();
/*MimeMessage mimeMessage=new MimeMessage(session);
String msgId=mimeMessage.getMessageID();*/
String from = fromAddress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
//message.setFlag(Flags.Flag.SEEN, true);
String contentType = message.getContentType();
String receivedDate=message.getReceivedDate().toString();
Enumeration headeinfo=message.getAllHeaders();
System.out.println("receivedDate" +receivedDate);
// int messageNo=message.get
String messageContent = "";
String modifiedsubject=subject.toUpperCase().replaceAll("\\s+", "");
//System.out.println("modifiedsubject name is:" + modifiedsubject);
// store attachment file name, separated by comma
String attachmentname = "";
//if(modifiedsubject.contains("SELLMYCAR")&& msgId.equals(emailmessageID)){
if(modifiedsubject.contains("SELLMYCAR")){
if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
/*String fileName = part.getFileName();
attachmentname = fileName;*/
//String ESBMessageID=(String) context.getProperty("MessageID");
// part.setFileName(emailmessageID+":"+new Date());
String fileName = part.getFileName();
//String fileName = part.getFileName().substring(0, 10)+"_"+emailmessageID+"_"+new Date();
part.saveFile(tempDirectory + File.separator + fileName);
System.out.println("Files are downloaded into "+ tempDirectory+" successfully");
if (attachmentname.length() > 1) {
attachmentname = attachmentname.substring(0, attachmentname.length());
}
/*FileMove Process*/
moveFile(tempDirectory,fileName,saveDirectory,transactionID);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
// print out details of each message
System.out.println("Message #" + (i + 1) + ":");
System.out.println("\t From: " + from);
//System.out.println("\t UserName: " + name);
System.out.println("\t Subject: " + subject);
System.out.println("\t Sent Date: " + sentDate);
//System.out.println("\t from: " + from);
System.out.println("\t Attachments: " + attachmentname);
System.out.println("\t LocalDownloadpath: " + saveDirectory);
} else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
/*need // print out details of each message
System.out.println("Message #" + (i + 1) + ":");
System.out.println("\t From: " + from);
System.out.println("\t UserName: " + name);
System.out.println("\t Subject: " + subject);
System.out.println("\t Sent Date: " + sentDate);
System.out.println("\t UserMailID: " + email);
System.out.println("\t Attachments: " + attachmentname);
System.out.println("\t LocalDownloadpath: " + saveDirectory);*/
}
}
// disconnect
folderInbox.close(false);
store.close();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
String protocol = "imap";
String host = "imap.gmail.com";
String port = "993";
String userName = "testmail@gmail.com";
String password = "password";
String tempDirectory = "D:\\Test\\SellMyCarImages/Temp";
String saveDirectory = "D:\\Test\\SellMyCarImages/Success";
String transactionID="urn:uuid:e9f1aa01-a18f-4ab4-aad3-0760ce304c87";
transactionID=transactionID.substring(transactionID.lastIndexOf(":")+1);
//System.out.println("saveDirectory"+saveDirectory);
String emailmessageId="16cb0e4i30c18f11";
setSaveDirectory(saveDirectory);
try {
downloadEmailAttachments(protocol, host, port, userName, password, tempDirectory,saveDirectory,transactionID,emailmessageId);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我希望此类仅是emailmessageID
的{{1}}的下载附件。不适用于所有邮件或相关主题等。