Retrieve and Manage Messages from Mail Server
Get Mailbox Information
We can get information about the mailbox such as the number of messages and the mailbox size using the GetMailBoxSize and GetMailBoxInfo methods of the Pop3Client class.
- The GetMailBoxSize method returns the size of the mailbox in bytes.
- The GetMailBoxInfo method returns an object of type Pop3MailBoxInfo.
It is also possible to get the number of messages using the MessageCount property and the size using the OccupiedSize property of the Pop3MailBoxInfo class. The following sample code shows how to get information about the mailbox. It shows how to:
- Create a Pop3Client.
- Connect to a POP3 server.
- Get the size of the mailbox.
- Get mailbox info.
- Get the number of messages in the mailbox.
- Get the occupied size.
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.Host = "pop.gmail.com";
client.Username = "your.username@gmail.com";
client.Password = "your.password";
client.Port = 995;
client.SecurityOptions = SecurityOptions.Auto;
// Get the size of the mailbox, Get mailbox info, number of messages in the mailbox
long nSize = client.GetMailboxSize();
Console.WriteLine("Mailbox size is " + nSize + " bytes.");
Pop3MailboxInfo info = client.GetMailboxInfo();
int nMessageCount = info.MessageCount;
Console.WriteLine("Number of messages in mailbox are " + nMessageCount);
long nOccupiedSize = info.OccupiedSize;
Console.WriteLine("Occupied size is " + nOccupiedSize);
Retrieve Email Count in Mailbox
The following code snippet shows you how to count the email messages in a mailbox.
Pop3Client client = new Pop3Client("pop3.server.com", "username", "password");
try
{
client.SecurityOptions = SecurityOptions.Auto;
int i = client.GetMessageCount();
Console.WriteLine("Message count: " + i);
}
catch (Pop3Exception ex)
{
Console.WriteLine("Error:" + ex.ToString());
}
Aspose.Email lets developers work with emails in many different ways. For example, they can retrieve header information before deciding whether to download an email. Or they can retrieve emails from a server and save them without parsing them (quicker) or after parsing them (slower).
Retrieve Email Headers
Email headers can give us information about an email message that we can use to decide whether or not to retrieve the whole email message. Typically, the header information contains sender, subject, received date, etc. (Email headers are described in detail in Customizing Email Headers. The following examples show how to retrieve email headers from a POP3 server by the message sequence number.
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username. password, Port and SecurityOptions for your client
client.Host = "pop.gmail.com";
client.Username = "your.username@gmail.com";
client.Password = "your.password";
client.Port = 995;
client.SecurityOptions = SecurityOptions.Auto;
try
{
HeaderCollection headers = client.GetMessageHeaders(1);
for (int i = 0; i < headers.Count; i++)
{
// Display key and value in the header collection
Console.Write(headers.Keys[i]);
Console.Write(" : ");
Console.WriteLine(headers.Get(i));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
client.Dispose();
}
Retrieve Email Messages
The MailMessage class contains several properties and methods for manipulating email content. By using FetchMessage method of the Pop3Client class, you can get a MailMessage instance directly from the POP3 server. The following code snippet shows you how to retrieve a complete email message from the POP3 server.
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.Host = "pop.gmail.com";
client.Username = "your.username@gmail.com";
client.Password = "your.password";
client.Port = 995;
client.SecurityOptions = SecurityOptions.Auto;
try
{
int messageCount = client.GetMessageCount();
// Create an instance of the MailMessage class and Retrieve message
MailMessage message;
for (int i = 1; i <= messageCount; i++)
{
message = client.FetchMessage(i);
Console.WriteLine("From:" + message.From);
Console.WriteLine("Subject:" + message.Subject);
Console.WriteLine(message.HtmlBody);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
client.Dispose();
}
Retrieve Message Summary with Unique Id
The POP3 Client can retrieve message summary information from the server using the unique id of the message. This provides quick access to the message short information without first retrieving the complete message from the server. The following code snippet shows you how to retrieve message summary information.
string uniqueId = "unique id of a message from server";
Pop3Client client = new Pop3Client("host.domain.com", 456, "username", "password");
client.SecurityOptions = SecurityOptions.Auto;
Pop3MessageInfo messageInfo = client.GetMessageInfo(uniqueId);
if (messageInfo != null)
{
Console.WriteLine(messageInfo.Subject);
Console.WriteLine(messageInfo.Date);
}
List Messages with MultiConnection
Pop3Client provides a UseMultiConnection property which can be used to create multiple connections for heavy operations. You may also set the number of connections to be used during multiconnection mode by using Pop3Client.ConnectionsQuantity. The following code snippet demonstrates the use of the multiconnection mode for listing messages and compares its performance with single connection mode.
// Create an instance of the Pop3Client class
Pop3Client pop3Client = new Pop3Client();
pop3Client.Host = "<HOST>";
pop3Client.Port = 995;
pop3Client.Username = "<USERNAME>";
pop3Client.Password = "<PASSWORD>";
pop3Client.ConnectionsQuantity = 5;
pop3Client.UseMultiConnection = MultiConnectionMode.Enable;
DateTime multiConnectionModeStartTime = DateTime.Now;
Pop3MessageInfoCollection messageInfoCol1 = pop3Client.ListMessages();
TimeSpan multiConnectionModeTimeSpan = DateTime.Now - multiConnectionModeStartTime;
pop3Client.UseMultiConnection = MultiConnectionMode.Disable;
DateTime singleConnectionModeStartTime = DateTime.Now;
Pop3MessageInfoCollection messageInfoCol2 = pop3Client.ListMessages();
TimeSpan singleConnectionModeTimeSpan = DateTime.Now - singleConnectionModeStartTime;
Console.WriteLine("multyConnectionModeTimeSpan: " + multiConnectionModeTimeSpan.TotalMilliseconds);
Console.WriteLine("singleConnectionModeTimeSpan: " + singleConnectionModeTimeSpan.TotalMilliseconds);
double performanceRelation = singleConnectionModeTimeSpan.TotalMilliseconds / multiConnectionModeTimeSpan.TotalMilliseconds;
Console.WriteLine("Performance Relation: " + performanceRelation);
Fetch Messages from Server and Save to Disc
Save Message to Disk without Parsing
If you want to download email messages from the POP3 server without parsing them, use the Pop3Client class SaveMessage function. The SaveMessage function does not parse the email message so it is faster than the FetchMessage function. The following code snippet shows how to save a message by its sequence number. In this case, the SaveMessage method saves the message in the original EML format without parsing it.
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_POP3();
string dstEmail = dataDir + "InsertHeaders.eml";
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.Host = "pop.gmail.com";
client.Username = "your.username@gmail.com";
client.Password = "your.password";
client.Port = 995;
client.SecurityOptions = SecurityOptions.Auto;
try
{
// Save message to disk by message sequence number
client.SaveMessage(1, dstEmail);
client.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 ");
Parse Message Before Saving
The following code snippet uses the Pop3Client FetchMessage method to retrieve a message from a POP3 server by its sequence number, then save the message to disk using the subject as the file name.
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_POP3();
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username and password, Port and SecurityOptions for your client
client.Host = "pop.gmail.com";
client.Username = "your.username@gmail.com";
client.Password = "your.password";
client.Port = 995;
client.SecurityOptions = SecurityOptions.Auto;
try
{
// Fetch the message by its sequence number and Save the message using its subject as the file name
MailMessage msg = client.FetchMessage(1);
msg.Save(dataDir + "first-message_out.eml", SaveOptions.DefaultEml);
client.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(Environment.NewLine + ex.Message);
}
finally
{
client.Dispose();
}
Fetch Group Messages
Pop3Client provides a FetchMessages method which accepts iterable of Sequence Numbers or Unique ID and returns a list of MailMessage. The following code snippet demonstrates the use of the FetchMessages method to fetch messages by Sequence Numbers and Unique ID.
// Create an instance of the Pop3Client class
Pop3Client pop3Client = new Pop3Client();
pop3Client.Host = "<HOST>";
pop3Client.Port = 995;
pop3Client.Username = "<USERNAME>";
pop3Client.Password = "<PASSWORD>";
Pop3MessageInfoCollection messageInfoCol = pop3Client.ListMessages();
Console.WriteLine("ListMessages Count: " + messageInfoCol.Count);
int[] sequenceNumberAr = messageInfoCol.Select((Pop3MessageInfo mi) => mi.SequenceNumber).ToArray();
string[] uniqueIdAr = messageInfoCol.Select((Pop3MessageInfo mi) => mi.UniqueId).ToArray();
IList<MailMessage> fetchedMessagesBySNumMC = pop3Client.FetchMessages(sequenceNumberAr);
Console.WriteLine("FetchMessages-sequenceNumberAr Count: " + fetchedMessagesBySNumMC.Count);
IList<MailMessage> fetchedMessagesByUidMC = pop3Client.FetchMessages(uniqueIdAr);
Console.WriteLine("FetchMessages-uniqueIdAr Count: " + fetchedMessagesByUidMC.Count);
Detect New Messages on the Server
With POP3 accounts, you can leave messages on the server when downloading and reading them. Leaving emails on the server means that they remain available to other applications and devices — for example, when a user accesses their email from several devices. You might also want to download only messages that meet some special criteria.
When messages are downloaded but not deleted, they stay on the server. The first time a download process runs, all the required messages are downloaded to the local database. But the second time it runs, the same messages are downloaded again because they are still on the server, which causes duplicate records. To solve this issue, use the Pop3MessageInfo.UniqueId property to check whether a message has already been downloaded. The message’s unique ID must be stored in the database, where it serves as the search key for detecting new messages.
To identify new emails from a list of messages on a POP3 server:
- Connect to the server.
- Get a list of messages.
- For each message, check whether its unique ID already exists in your local data store.
- Save only the new messages to the database.
The process is faster when you fetch all the unique IDs of stored messages into a hash table and search the hash table instead of querying the database for each message in the loop. Instead of querying the database for each message, requiring many database calls, this method only requires one call. The following code snippet shows you how to detect new email messages on the POP3 server.
public static void Run()
{
try
{
// Connect to the POP3 mail server and check messages.
Pop3Client pop3Client = new Pop3Client("pop.domain.com", 993, "username", "password");
// List all the messages
Pop3MessageInfoCollection msgList = pop3Client.ListMessages();
foreach (Pop3MessageInfo msgInfo in msgList)
{
// Get the POP3 message's unique ID
string strUniqueID = msgInfo.UniqueId;
// Search your local database or data store on the unique ID. If a match is found, the message is already
// downloaded. Otherwise download and save it.
if (SearchPop3MsgInLocalDB(strUniqueID) == true)
{
// The message is already in the database. Nothing to do with this message. Go to the next message.
}
else
{
// Save the message
SavePop3MsgInLocalDB(msgInfo);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void SavePop3MsgInLocalDB(Pop3MessageInfo msgInfo)
{
// Open the database connection according to your database. Use public properties (for example msgInfo.Subject)
// and store them in the database, then run the query to store the record.
}
private static bool SearchPop3MsgInLocalDB(string strUniqueID)
{
// Open the database connection according to your database. Use strUniqueID in the search query to find existing
// records. Return true if the record is found, otherwise return false.
return false;
}