MailClient Class


Provides properties and methods for receiving messages and managing IMAP4 folder.

System.Object
    EAGetMail.MailClient

[Visual Basic]
Public Class MailClient
[C#]
public class MailClient
[C++]
public ref class MailClient
[JScript]
public class MailClient

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Public Constructors

MailClient Constructor Initializes a new instance of the MailClient class.

Public Properties

ClientCertificate The certificate to enable the SSL connection.
Connected Gets whether the server is connected.
Conversation Gets the latest conversation beween mail server and mail client.
CurrentMailServer Gets the latest mail server that is used to receive e-mail message.
GetMailInfosParam Set search filters/parameters for GetMailInfos method.
Imap4Folders Gets all folders on IMAP4/Exchange server.
LogFileName Gets or sets the log file name for mail transaction.
SelectedFolder Gets current selected folder of IMAP4/Exchange server.
Tag

Gets or sets an object that contains data to associate with the MailClient.

Timeout

Gets or sets the maximum time interval(seconds) the object will wait for a response from server before returning an error.

Public Methods

Append Appends an email to specified IMAP4/Exchange folder.
AppendEx Appends an email to specified IMAP4/Exchange folder with flags.
CancelWaitEmail Cancel WaitNewEmail method.
ChangeMailFlags Changes the flags of an email on IMAP4 server.
Close Closes the connection to server forcely.
Connect Connects a mail server.
Copy Copies a specified email from selected folder to another folder on IMAP4/Exchange server.
Move Moves a specified email from selected folder to another folder on IMAP4/Exchange server.
CreateFolder Creates a folder on IMAP4/Exchange server.
Delete Marks the specified email as deleted.
DeleteFolder Removes the specified folder from IMAP4/Exchange server.
Expunge Expunges the deleted emails in current selected folder on IMAP4 server.
GetCategories Get categories of the email message, only EWS and Graph API support this method.
GetFollowUpFlag Get follow-up flag of the email message, only EWS and Graph API support this method.
GetMail Receives a specified email from mail server.
GetMailCount Get total emails count on POP3/IMAP4/MS Exchange Server.
GetMailHeader Receives a specified email headers from mail server.
GetMailInfos Retrieves all emails' information on mail server.
GetMailsByQueue Retrieves emails by EAGetMail Service in background.
Logout Disconnects with IMAP4 server without expunging the deleted emails.
MarkAsRead Change the email read flag on IMAP4/Exchange server.
QueryEWSPublicFolders Retrieves all public folders from MS Exchange Server 2007 or later version.
Quit Disconnects the mail server and expunging the deleted emails.
Reset Undeletes the deleted emails on mail server.
RenameFolder Rename the specified folder on IMAP4/Exchange server.
SearchMail Searchs emails in sepecified IMAP4 folder.
SelectFolder Selects an IMAP4/Exchange folder to operate.
SetCategories Set categories to the email message, only EWS and Graph API support this method.
SetFollowUpFlag Set follow-up flag to the email message, only EWS and Graph API support this method.
SubscribeFolder Subscribes an IMAP4 folder.
UnsubscribeFolder Unsubscribes an IMAP4 folder.
Undelete Undeletes specified deleted email on IMAP4 server.
WaitNewEmail Get notification of new email event on IMAP4 server and MS Exchange Server.

Public Events

OnAuthorized Occurs when mail server has authorized the user.
OnConnected Occurs when the client has connected to mail server successfully.
OnIdle Occurs when the client is connecting server or waiting response from mail server.
OnQuit Occurs when the client is disconnecting the mail server.
OnReceiveResponse Occurs when the client has received a response from mail server.
OnReceivingDataStream Occurs when the client is receiving the e-mail data from mail server.
OnSecuring Occurs when the client is establishing the SSL connection.
OnSendCommand Occurs when the client has sent a command to the mail server.
OnSendingDataStream Occurs when the client is sending the e-mail data (Append) to the IMAP4 server.

Example

[Visual Basic, C#, C++] The following example demonstrates how To retrieve email with EAGetMail POP3 & IMAP Component, but it doesn't demonstrates the events and mail parsing usage. To get the full samples of EAGetMail, please refer to Samples section.

[VB - Retrieve Email from POP3/IMAP4/MS Exchange Server]
Imports System
Imports System.Globalization
Imports System.IO
Imports System.Text
Imports EAGetMail

Public Class TestClass
    ' Generate an unqiue email file name based on date time.
    Shared Function _generateFileName(ByVal sequence As Integer) As String
        Dim currentDateTime As DateTime = DateTime.Now
        Return String.Format("{0}-{1:000}-{2:000}.eml",
                            currentDateTime.ToString("yyyyMMddHHmmss", New CultureInfo("en-US")),
                            currentDateTime.Millisecond,
                            sequence)
    End Function

    Public Sub ReceiveMail(server As String, user As String, password As String, useSsl As Boolean)

        Try
            ' Create a folder named "inbox" under current directory
            ' to save the email retrieved.
            Dim localInbox As String = String.Format("{0}\inbox", Directory.GetCurrentDirectory())

            ' If the folder is not existed, create it.
            If Not Directory.Exists(localInbox) Then
                Directory.CreateDirectory(localInbox)
            End If

            ' To receive email from IMAP4 server, please change
            ' ServerProtocol.Pop3 to ServerProtocol.Imap4 in MailServer constructor

            ' To receive email with Exchange Web Service, please change
            ' ServerProtocol.Pop3 to ServerProtocol.ExchangeEWS to MailServer constructor

            ' To receive email with Exchange WebDAV, please change
            ' ServerProtocol.Pop3 to ServerProtocol.ExchangeWebDAV to MailServer constructor

            ' Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007
            ' Or later version, POP3/IMAP4 service Is disabled by default. If you don't want to use POP3/IMAP4
            ' to download email from Exchange Server, you can use Exchange Web Service (Exchange 2007-2019 Or
            ' later version) Or WebDAV (Exchange 2000/2003) protocol.

            ' Most modern email server require SSL/TLS connection, 
            ' set useSsl to true Is recommended.
            Dim oServer As New MailServer(server, user, password, useSsl,
                        ServerAuthType.AuthLogin, ServerProtocol.Pop3)

            ' POP3 port Is 110, POP3 SSL port Is 995
            ' IMAP4 port Is 143,  IMAP4 SSL port Is 993.
            ' EWS/WebDAV, please ignore Port property.
            If oServer.Protocol = ServerProtocol.Pop3 Then
                oServer.Port = If(useSsl, 995, 110)
            ElseIf oServer.Protocol = ServerProtocol.Imap4 Then
                oServer.Port = If(useSsl, 993, 143)
            End If

            Console.WriteLine("Connecting server ...")
            Dim oClient As New MailClient("TryIt")
            oClient.Connect(oServer)

            Console.WriteLine("Retrieving email list ...")
            Dim infos() As MailInfo = oClient.GetMailInfos()

            Console.WriteLine("Total {0} email(s)", infos.Length)

            For i As Integer = 0 To infos.Length - 1
                Console.WriteLine("Checking {0}/{1} ...", i + 1, infos.Length)
                Dim info As MailInfo = infos(i)

                Console.WriteLine("UIDL: {0}", info.UIDL)
                Console.WriteLine("Index: {0}", info.Index)
                Console.WriteLine("Size: {0}", info.Size)
                ' IMAP4MailFlags is supported by IMAP only.
                Console.WriteLine("Flags: {0}", info.IMAP4MailFlags)
                ' POP3 protocol doesn't support read flag.
                Console.WriteLine("Read: {0}", info.Read)
                Console.WriteLine("Deleted: {0}", info.Deleted)

                ' Generate an unqiue email file name based on date time.
                Dim fileName As String = _generateFileName(i + 1)
                Dim fullPath As String = String.Format("{0}\{1}", localInbox, fileName)

                Console.WriteLine("Downloading {0}/{1} ...", i + 1, infos.Length)
                Dim oMail As Mail = oClient.GetMail(info)

                ' Save email to local disk
                oMail.SaveAs(fullPath, True)

                ' Mark email as deleted on server.
                Console.WriteLine("Deleting ... {0}/{1}", i + 1, infos.Length)
                oClient.Delete(info)
            Next

            Console.WriteLine("Disconnecting ...")
            ' Delete method just mark the email as deleted, 
            ' Quit method expunge the emails from server permanently.
            oClient.Quit()

            Console.WriteLine("Completed!")
        Catch ep As Exception
            Console.WriteLine("Error: {0}", ep.Message)
        End Try

    End Sub
End Class


[C# - Retrieve Email from POP3/IMAP4/MS Exchange Server] using System; using System.IO; using System.Globalization; using System.Text; using EAGetMail; class TestClass { // Generate an unqiue email file name based on date time static string _generateFileName(int sequence) { DateTime currentDateTime = DateTime.Now; return string.Format("{0}-{1:000}-{2:000}.eml", currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")), currentDateTime.Millisecond, sequence); } public void ReceiveMail(string server, string user, string password, bool useSsl) { try { // Create a folder named "inbox" under current directory // to save the email retrieved. string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory.Exists(localInbox)) { Directory.CreateDirectory(localInbox); } // To receive email from IMAP4 server, please change // ServerProtocol.Pop3 to ServerProtocol.Imap4 in MailServer constructor // To receive email with Exchange Web Service, please change // ServerProtocol.Pop3 to ServerProtocol.ExchangeEWS to MailServer constructor // To receive email with Exchange WebDAV, please change // ServerProtocol.Pop3 to ServerProtocol.ExchangeWebDAV to MailServer constructor // Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007 // or later version, POP3/IMAP4 service is disabled by default. If you don't want to use POP3/IMAP4 // to download email from Exchange Server, you can use Exchange Web Service (Exchange 2007-2019 or // later version) or WebDAV (Exchange 2000/2003) protocol. // Most modern email server require SSL/TLS connection, // set useSsl to true is recommended. MailServer oServer = new MailServer(server, user, password, useSsl, ServerAuthType.AuthLogin, ServerProtocol.Pop3); // POP3 port is 110, POP3 SSL port is 995 // IMAP4 port is 143, IMAP4 SSL port is 993. // EWS/WebDAV, please ignore Port property. if (oServer.Protocol == ServerProtocol.Pop3) { oServer.Port = (useSsl) ? 995 : 110; } else if (oServer.Protocol == ServerProtocol.Imap4) { oServer.Port = (useSsl) ? 993 : 143; } Console.WriteLine("Connecting server ..."); MailClient oClient = new MailClient("TryIt"); oClient.Connect(oServer); Console.WriteLine("Retreiving email list ..."); MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} email(s)", infos.Length); for (int i = 0; i < infos.Length; i++) { Console.WriteLine("Checking {0}/{1} ...", i+1, infos.Length); MailInfo info = infos[i]; Console.WriteLine("UIDL: {0}", info.UIDL); Console.WriteLine("Index: {0}", info.Index); Console.WriteLine("Size: {0}", info.Size); // IMAP4MailFlags is supported by IMAP4 protocol only. Console.WriteLine("Flags: {0}", info.IMAP4MailFlags); // POP3 protocol doesn't support read flag Console.WriteLine("Read: {0}", info.Read); Console.WriteLine("Deleted: {0}", info.Deleted); // Generate an unqiue email file name based on date time. string fileName = _generateFileName(i + 1); string fullPath = string.Format("{0}\\{1}", localInbox, fileName); Console.WriteLine("Downloading {0}/{1} ...", i + 1, infos.Length); Mail oMail = oClient.GetMail(info); // Save mail to local file oMail.SaveAs(fullPath, true); // Mark the email as deleted on server. Console.WriteLine("Deleting ... {0}/{1}", i + 1, infos.Length); oClient.Delete(info); } Console.WriteLine("Disconnecting ..."); // Delete method just mark the email as deleted, // Quit method expunge the emails from server permanently. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine("Error: {0}", ep.Message); } } }
[C++/CLI - Retrieve Email from POP3/IMAP4/MS Exchange Server] using namespace System; using namespace System::Globalization; using namespace System::IO; using namespace EAGetMail; //add EAGetMail namespace // Generate an unqiue email file name based on date time static String ^ _generateFileName(int sequence) { DateTime currentDateTime = DateTime::Now; return String::Format("{0}-{1:000}-{2:000}.eml", currentDateTime.ToString("yyyyMMddHHmmss", gcnew CultureInfo("en-US")), currentDateTime.Millisecond, sequence); } void ReceiveMail(String ^server, String ^user, String ^password, bool useSsl) { try { // Create a folder named "inbox" under current directory // to save the email retrieved. String ^localInbox = String::Format("{0}\\inbox", Directory::GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory::Exists(localInbox)) { Directory::CreateDirectory(localInbox); } // To receive email from IMAP4 server, please change // ServerProtocol.Pop3 to ServerProtocol.Imap4 in MailServer constructor // To receive email with Exchange Web Service, please change // ServerProtocol.Pop3 to ServerProtocol.ExchangeEWS to MailServer constructor // To receive email with Exchange WebDAV, please change // ServerProtocol.Pop3 to ServerProtocol.ExchangeWebDAV to MailServer constructor // Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007 // or later version, POP3/IMAP4 service is disabled by default. If you don't want to use POP3/IMAP4 // to download email from Exchange Server, you can use Exchange Web Service (Exchange 2007-2019 or // later version) or WebDAV (Exchange 2000/2003) protocol. // Most modern email server require SSL/TLS connection, // set useSsl to true is recommended. MailServer ^oServer = gcnew MailServer(server, user, password, useSsl, ServerAuthType::AuthLogin, ServerProtocol::Pop3); // POP3 port is 110, POP3 SSL port is 995 // IMAP4 port is 143, IMAP4 SSL port is 993. // EWS/WebDAV, please ignore Port property. if (oServer->Protocol == ServerProtocol::Pop3) { oServer->Port = (useSsl) ? 995 : 110; } else if (oServer->Protocol == ServerProtocol::Imap4) { oServer->Port = (useSsl) ? 993 : 143; } Console::WriteLine("Connecting server ..."); MailClient ^oClient = gcnew MailClient("TryIt"); oClient->Connect(oServer); Console::WriteLine("Retreiving email list ..."); array<MailInfo^>^infos = oClient->GetMailInfos(); Console::WriteLine("Total {0} email(s)", infos->Length); for (int i = 0; i < infos->Length; i++) { Console::WriteLine("Checking {0}/{1}", i + 1, infos->Length); MailInfo ^info = infos[i]; Console::WriteLine("UIDL: {0}", info->UIDL); Console::WriteLine("Index: {0}", info->Index); Console::WriteLine("Size: {0}", info->Size); // IMAP4MailFlags is supported by IMAP4 protocol only Console::WriteLine("Flags: {0}", info->IMAP4MailFlags); // POP3 doesn't support read flag Console::WriteLine("Read: {0}", info->Read); Console::WriteLine("Deleted: {0}", info->Deleted); // Generate an unqiue email file name based on date time String^ fileName = _generateFileName(i + 1); String^ fullPath = String::Format("{0}\\{1}", localInbox, fileName); Console::WriteLine("Downloading {0}/{1}", i + 1, infos->Length); Mail ^oMail = oClient->GetMail(info); // Save email to local disk oMail->SaveAs(fullPath, true); // Mark email as deleted on server. Console::WriteLine("Deleting ... {0}/{1}", i + 1, infos->Length); oClient->Delete(info); } Console::WriteLine("Disconnecting ..."); // Delete method just mark the email as deleted, // Quit method expunge the emails from server permanently. oClient->Quit(); Console::WriteLine("Completed!"); } catch (Exception ^ep) { Console::WriteLine("Error: {0}", ep->Message); } }

See Also

User Authentication and SSL/TLS Connection
Mail Class

Online Tutorials

Read Email and Parse Email in C# - Tutorial
Read Email and Parse Email in VB.NET - Tutorial
Read Email and Parse Email C++/CLI - Tutorial

Read Email over SSL/TLS Connection in C# - Tutorial
Read Email from Gmail Account in C# - Tutorial
Read Email from Yahoo Account in C# - Tutorial
Read Email from Hotmail Account in C# - Tutorial

Read Email over SSL/TLS Connection in VB.NET - Tutorial
Read Email from Gmail Account in VB.NET - Tutorial
Read Email from Yahoo Account in VB.NET - Tutorial
Read Email from Hotmail Account in VB.NET - Tutorial

Read Email over SSL/TLS Connection C++/CLI - Tutorial
Read Email from Gmail Account in C++/CLI - Tutorial
Read Email from Yahoo Account in C++/CLI - Tutorial
Read Email from Hotmail Account in C++/CLI - Tutorial