Exception while adding bulk messages to pst

Hi,


I have created pst file and adding messages to pst. I am getting casting exception can not cast to IGenericEnumerable

Exception in thread “main” java.lang.ClassCastException: mithi.files.pst.bulkadd.MapiMessageCollection cannot be cast to com.aspose.email.system.collections.generic.IGenericEnumerable
at mithi.files.pst.GeneratePSTApp.createMailArchive(GeneratePSTApp.java:115)
at mithi.export.GenerateMailArchive.generateFiles(GenerateMailArchive.java:73)
at mithi.export.GenerateMailArchive.generateFiles(GenerateMailArchive.java:73)
at mithi.export.ExportMailAsPSTApp.generateMailArchiveFiles(ExportMailAsPSTApp.java:19)
at mithi.export.ExportMailArchiveApp.execute(ExportMailArchiveApp.java:37)

at mithi.export.ExportMailArchiveApp.execute(ExportMailArchiveApp.java:37)
at mithi.apps.jobs.RestoreMailApp.execute(RestoreMailApp.java:43)
at mithi.apps.jobs.RestoreMailApp.execute(RestoreMailApp.java:43)
at mithi.apps.jobs.RestoreMailApp.main(RestoreMailApp.java:70)


My function is:

szFileName = “test.pst”;
pst = PersonalStorage.create(szFileName, FileFormatVersion.Unicode);
FolderInfo folder = pst.getRootFolder().addSubFolder(“testfolder”).getTextValue());

folder.addMessages((IGenericEnumerable) new MapiMessageCollection(arMsg)); //Message[] arMsg


And collection is as:


package mithi.files.pst.bulkadd;


import java.util.Iterator;
import javax.mail.Message;
import javax.mail.MessagingException;

import com.aspose.email.MailMessage;
import com.aspose.email.MapiMessage;
import com.sun.mail.imap.IMAPMessage;

// For complete examples and data files, please go to GitHub - aspose-email/Aspose.Email-for-Java: Aspose.Email for Java Examples
public class MapiMessageCollection implements Iterable {
private Message[] arMsgs;

public MapiMessageCollection(Message[] arMsgs) {
this.arMsgs = arMsgs;
}

public Iterator iterator() {
return new MapiMessageEnumerator(arMsgs);
}

public class MapiMessageEnumerator implements Iterator {
private Message[] msgs;

private int position = -1;

public MapiMessageEnumerator(Message[] oMsgs) {
this.msgs = oMsgs;
}

public boolean hasNext() {
position++;
return (position < this.msgs.length);
}

public void reset() {
position = -1;
}

public MapiMessage next() {
final IMAPMessage oImapMsg = (IMAPMessage)msgs[position];
// create mailmessage from msg and convert to MapiMessage
MailMessage oMailMsg1 = new MailMessage();
try {
MailMessage oMailMsg = MailMessage.load(oImapMsg.getMimeStream());
return MapiMessage.fromMailMessage(oMailMsg);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return MapiMessage.fromMailMessage(oMailMsg1);
}

public void dispose() {
}

public void remove() {
throw new UnsupportedOperationException();
}
}
}

I wanted to add bulk messages to improve performance, it is taking too much time to create pst if mailstore size is greater than 200mb.

Hi Archana,

Thank you for contacting Aspose support team.

You may use following sample code to add bulk messages in PST. Please give it a try and share the feedback.

static private void TestCode()
{
    String dataDir = "MessagesPath/";
    String szFileName = "test.pst";
    PersonalStorage pst = PersonalStorage.create("PstDestination/" + szFileName, FileFormatVersion.Unicode);
    FolderInfo folder = pst.getRootFolder().addSubFolder("myInbox");
    folder.addMessages((IGenericEnumerable) new MapiMessageCollection(dataDir));
}

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
static public class MapiMessageCollection implements IGenericEnumerable 
{
    private String path;

    public MapiMessageCollection(String path) 
    {
        this.path = path;
    }

    public IGenericEnumerator iterator() 
    {
        return new MapiMessageEnumerator(this.path);
    }

    public class MapiMessageEnumerator implements IGenericEnumerator
    {
        private String[] files;
        private int position = -1;
    
        public MapiMessageEnumerator(String path)
        {
            //this.files = Directory.getFiles(path);
             
            File folder = new File(path);
            File[] listOfFiles = folder.listFiles();
            files = new String[listOfFiles.length];
            int iCounter = 0;
    		
            for (File file : listOfFiles)
            {
                if (file.isFile())
                {
                    files[iCounter] = file.getPath();
                    iCounter++;
                }
            }
        }
    
        public boolean hasNext()
        {
            position++;
            return (position < this.files.length);
        }
    
        public void reset()
        {
            position = -1;
        }
    
        public MapiMessage next()
        {
            try
            {
                return MapiMessage.fromFile(files[position]);
            }
            catch (IndexOutOfBoundsException e)
            {
                throw new IllegalStateException();
            }
        }
    
        public void dispose()
        {
        }
    
        public void remove()
        {
            throw new UnsupportedOperationException();
        }
    }
}

class Directory 
{
    public String[] getFiles(String path) 
	{
        if (path == null)
            throw new RuntimeException("path");

        return getFiles(path, "*.*");
    }

    public String[] getFiles(String path, final String searchPattern) 
	{
        if (path == null)
            throw new RuntimeException("path");

    java.io.File dir = new java.io.File(path);
    
    FilenameFilter filter = new PatternFileFilter(searchPattern, true);
    
    String[] result = new String[0];
    String[] fileNames = dir.list(filter);
    
	if (fileNames != null) 
	{
        result = new String[fileNames.length];
    
        for (int i = 0; i < result.length; i++) 
		{
            result[i] = fileNames[i];
        }
    }
	
    return result;
	
    }
}

class PatternFileFilter implements FilenameFilter 
{
    private Pattern mPattern;
    private boolean _isFile;

    public PatternFileFilter(String pattern, boolean isFile) 
	{
        if (pattern == "*.*") 
		{
            mPattern = Pattern.compile("^.*$");
        } 
		else 
		{
            pattern = pattern.replace(".", "\\.");
            mPattern = Pattern.compile("^" + pattern.replace("*", ".*").replace("?", ".") + "$", Pattern.CASE_INSENSITIVE);
        }
		
        _isFile = isFile;
    }

    public boolean accept(java.io.File dir, String name) 
	{
        String filePath = name;
        java.io.File file = new java.io.File(filePath);
        if ((_isFile && file.isFile()) || (!_isFile && file.isDirectory())) 
		{
            if (file.isFile()) 
			{
                if (!name.contains(".")) 
				{
                    String mask = mPattern.pattern();
                    
					if (mask.endsWith("..*$")) 
					{
                        mask = mask.replace("\\..*$", ".*$");
                    }
        
		            if (mask.endsWith(".$")) 
		            {
                        mask = mask.replace("\\.$", "$");
                    }
                    
					Pattern tmpPattern = Pattern.compile(mask);
                    return tmpPattern.matcher(name).find();
                }
           }
		   
            return mPattern.matcher(file.getName()).find();
        }
        else
		{
            return false;
        }
    }
}

Hi,

Thank you so much for the reply.

Exception solved, but i dont want to iterate over files I want to handle at protocol level.

I am passing java mail Message[] array to the collection and by getMimeStream want to create MapiMessage.

Now the problem is only message contents are displayed if I import generated pst file in outlook. Message header - to,cc,bcc, from etc not displayed at all.
<span style=“font-size: 9pt; font-family: “Courier New”;”>

Attaching sample pst file.

Mail headers not displayed only contents are displayed.

Hi Archana,


Could you please share the original EML/MSG files that are added to the PST? We need them to add to the PST file by ourselves for reproducing the issue at our end. We’ll investigate it for assisting you further.

Hi,

Thank you so much for the reply.
Attaching sample mails zip file. I want to bulk add mails to pst, also at IMAP protocol level, dont want to iterate over directory files ( as given in your example ).
I am using getMimeStream funciton of IMAPMessage to create MailMessage and creating MapiMessage from mailmessage. Using same technique need to add bulk messages.

Thank you.

Hi Archana,


Thank you for sharing the sample EML files. However, we are not able to reproduce this problem at our end using the sample code above that is the only method for adding messages to PST in bulk. I have attached the generated PST file here for your reference. I would request you to please share your sample code with us that we can execute at our end for investigating the issue further.

With respect to your inquiry related to doing the same at IMAP protocol level, you can download the emails from IMAP and then add them in bulk to PST from saved location. Please let us know if you have any other concern in this regard.

Hi,

Thanks for the reply but attachment is missing in your reply.

Hi,


Please find the PST file as attached here and let us know if you need any further assistance. We are sorry for missing it earlier as attachment.

My sample code is:

I have Message[] arMsg

Writing IMAP messages to file :
private void getImapMessagesToDir(File msgdir, Message[] arMsg) {
// TODO Auto-generated method stub

for(int i=0; i < arMsg.length; i++)
{
File eml;
try {
eml = File.createTempFile(“mail”, “.eml”, msgdir);
final OutputStream out = new FileOutputStream(eml);
arMsg[i].writeTo(out);
IOUtils.closeQuietly(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


In MapiMessageEnumerator next method:

public MapiMessage next()
{
try
{
MailMessage mail2 = MailMessage.load(files[position]);
return MapiMessage.fromMailMessage(mail2);
}
catch (IndexOutOfBoundsException e)
{
throw new IllegalStateException();
}
}

Still error in generated pst, message header not displayed and outlook restarted after opening this pst in outlook 2013.

Attaching sample java files with this.

Hi Archana,


We are working over your query and will soon share our findings with you here. We are sorry for the inconvenience caused to you.

Hi,


Any updates on this?

I am waiting for your reply.

Thanks.

Hi Archana,


We are sorry for a delayed response.

We investigated your files but due to compilation errors, we could not execute these at our end. However, we have prepared a simple Eclipse project that you can run at your end and share your feedback with us. We didn’t notice anything abnormal at our end as you have mentioned. Please try it at your end and if you face any issue, please share with us a sample runnable project that we can use at our end for investigating the issue further. We’ll assist you as soon as possible on this. Please make sure that you use the latest version of the API at your end.

Hi,


Thank you for the solution and it worked out. But now getting exception while adding some mails. These mails are calendar invitation mails. Attaching mails zip with this. Used same code given by you.

Hi Archana,


We have already created an issue for your this new problem and you can follow the new thread here: MailMessage.Load raises Exception

Please always create a new post if you face some different issue that needs to be logged separately. This will also help you in tracking your raises issues properly.