Email Attachment download by passing email message id using IMAP

二次信任 提交于 2019-12-11 15:36:24

问题


I want to download email Attachment(here image) from gmail for the particular email message id which comes from esb end, i have looked https://javaee.github.io/javamail/docs/api/javax/mail/search/MessageIDTerm.html and https://javaee.github.io/javamail/docs/api/javax/mail/search/SearchTerm.html, But didn't get attachment for particular Email MessageId.

I've tried:

Download process success for some other checks like unreadsearchterm, subjectTerm. But using MessageIdTerm way is not successful. After downloading, I'm moving that attachment to some other folder with some other name (while downloading, I'm not able to change the attachment name, so that using some temp folder here). Note: ESB returns messageID like 16cb0e2c30c18f11, that id is correct only, because it shows the correct email, while search directly in url after .*/inbox/{emailmessageid}. But if I open header, it shows some other id like ece641efe83480e9bf34c31738eea59e@www.something.com

package 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();
    }
}
}

I expect this class is download attachment only for emailmessageID, which comes from esb. Not for All mail or related subjects etc.

来源:https://stackoverflow.com/questions/58117780/email-attachment-download-by-passing-email-message-id-using-imap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!