Menu

IMAP Server

Aspose Marketplace

Include Namespaces

Please make sure to add the following namespaces before trying the code below

using Aspose.Email.Imap;
using Aspose.Email.Outlook.Pst;
using Aspose.Email.Outlook;

Connect to IMAP Server using Aspose.Email

You can connect to an IMAP server by using the following lines of code. If the server is SSL enabled then you will need to provide its SSL port otherwise default port i.e. 143 will be used for non SSL connection.

ImapClient client = new ImapClient(ServerURL, (SSLEnabled ? SSLPort : 143), Username, Password);
if (SSLEnabled)
{
    client.EnableSsl = true;
    client.SecurityMode = Aspose.Email.Imap.ImapSslSecurityMode.Implicit; // set security mode
}

Get folders list from IMAP Server

You can get list of Mailbox folders from IMAP Server using this line of code

ImapFolderInfoCollection folderInfoColl = client.ListFolders();

Get all messages from a Microsoft Exchange Folder

Once you get list of all folders from an IMAP Server Mailbox, you can use the Folder name to first select that folder and then get list of all messages in that folder.

client.SelectFolder(folderName);
ImapMessageInfoCollection msgInfoColl = client.ListMessages();

Get single message from IMAP Server

If you have bound all the messages to a GridView or some other control, upon selecting a single message you will need to get that single message again for showing its details or using it for any other purpose. You can use this single line of code to do that

MailMessage mail = client.FetchMessage(uniqueId);

Export entire IMAP Server folder to a PST file

Please check the following lines of code to export an entire folder to PST file

string outputFileName = System.Guid.NewGuid().ToString() + ".pst";
PersonalStorage pst = PersonalStorage.Create(outputFileName, FileFormatVersion.Unicode);
pst.RootFolder.AddSubFolder(folderName);
FolderInfo outfolder = pst.RootFolder.GetSubFolder(folderName);

client.SelectFolder(folderName);
ImapMessageInfoCollection messageInfoCollection = client.ListMessages();

foreach (ImapMessageInfo msg in messageInfoCollection)
{
    MailMessage mail = client.FetchMessage(msg.UniqueId);
    outfolder.AddMessage(MapiMessage.FromMailMessage(mail));
}

pst.Dispose();

Export selected messages from IMAP Server to a PST file

You can export selected IMAP messages to a PST file. Below is the code to do that

string outputFileName = System.Guid.NewGuid().ToString() + ".pst";
PersonalStorage pst = PersonalStorage.Create(outputFileName, FileFormatVersion.Unicode);
pst.RootFolder.AddSubFolder(folderName);
FolderInfo outfolder = pst.RootFolder.GetSubFolder(folderName);

client.SelectFolder(folderName);

foreach (string mUri in messagesUrisList)
{
    MailMessage mail = client.FetchMessage(mUri);
    outfolder.AddMessage(MapiMessage.FromMailMessage(mail));
}

pst.Dispose();