Ultimate Mail makes it easy for you to establish secure and non-secure connections to your IMAP servers.
To connect and authenticate to an IMAP server, you can perform the following steps
Imap
class.Connect
methods.Disconnect
method to close the IMAP session when done.
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the IMAP port with
// client.Connect("myserver", 143);
// Login to the server.
client.Authenticate("user", "password");
StringBuilder sb = new StringBuilder();
FolderCollection list = client.ListFolders();
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].Name);
}
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the IMAP port with
' client.Connect("myserver", 143);
' Login to the server.
client.Authenticate("user", "password")
Dim sb As New StringBuilder()
Dim list As FolderCollection = client.ListFolders()
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).Name)
Next i
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect("myserver", 143, SslSecurityMode.Explicit);
// Login to the server.
client.Authenticate("user", "password");
StringBuilder sb = new StringBuilder();
FolderCollection list = client.ListFolders();
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].Name);
}
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect("myserver", 143, SslSecurityMode.Explicit)
' Login to the server.
client.Authenticate("user", "password")
Dim sb As New StringBuilder()
Dim list As FolderCollection = client.ListFolders()
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).Name)
Next i
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()
Explicit connection and Implicit connection are two secure methods used to connect to a secure IMAP server. Ultimate Mail supports both Explicit and Implicit SSL modes.
It also allows you to upgrade an unsecured connection to secure or downgrade a secure connection to unsecured.
By default Imap
validates certificate received from the server automatically. However, you can extend the process for a specific purpose, like asking the user whether to accept or reject the server's certificate. You can easily customize the validation process by handling the CertificateReceived
event of the Imap
class.
The example following will show you how to do that:
public void HandleCertificateReceivedEvent()
{
// Create a new instance.
Imap client = new Imap();
client.CertificateReceived += client_CertificateReceived;
// Connect to the IMAP server.
client.Connect("myserver", 143, SslSecurityMode.Explicit);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
// ...
// Disconnect.
client.Disconnect();
}
/// <summary>
/// Returns all issues of the given certificate.
/// </summary>
/// <param name="status">The certificate verification result.</param>
/// <param name="code">The error code.</param>
/// <returns>Certificate problems.</returns>
private static string GetCertProblem(CertificateVerificationStatus status, int code)
{
switch (status)
{
case CertificateVerificationStatus.TimeNotValid:
return "Server's certificate has expired or is not valid yet.";
case CertificateVerificationStatus.Revoked:
return "Server's certificate has been revoked.";
case CertificateVerificationStatus.UnknownCa:
return "Server's certificate was issued by an unknown authority.";
case CertificateVerificationStatus.UntrustedRoot:
return "Server's certificate was issued by an untrusted authority.";
case CertificateVerificationStatus.IncompleteChain:
return "Server's certificate does not chain up to a trusted root authority.";
case CertificateVerificationStatus.Malformed:
return "Server's certificate is malformed.";
case CertificateVerificationStatus.CnNotMatch:
return "Server hostname does not match the certificate.";
case CertificateVerificationStatus.UnknownError:
return string.Format("Error {0:x} encountered while validating server's certificate.", code);
default:
return status.ToString();
}
}
void client_CertificateReceived(object sender, ComponentPro.Security.CertificateReceivedEventArgs e)
{
X509Certificate2 cert = e.ServerCertificates[0];
CertificateVerificationStatus status = e.Status;
CertificateVerificationStatus[] values = (CertificateVerificationStatus[])Enum.GetValues(typeof(CertificateVerificationStatus));
StringBuilder sbIssues = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
// Matches the validation status?
if ((status & values[i]) == 0)
continue;
// The issue is processed.
status ^= values[i];
sbIssues.AppendFormat("{0}\r\n", GetCertProblem(values[i], e.ErrorCode));
}
Console.WriteLine("Issue: " + sbIssues.ToString());
Console.WriteLine("Subject: " + cert.SubjectName.Name);
Console.WriteLine("Issuer: " + cert.IssuerName.Name);
Console.WriteLine("Effective Date: " + cert.NotBefore);
Console.WriteLine("Expiry Date: " + cert.NotAfter);
Console.ResetColor();
Console.Write("Do you want to accept this certificate (Add to trusted list, Yes, No) [a,y,n]?");
string response = Console.ReadLine().Trim().ToLower();
// Add certiticate of the issuer CA to the trusted list.
if (response == "a")
{
e.AddToTrustedRoot = true;
}
else if (response == "y")
{
e.Accept = true;
}
}
Public Sub HandleCertificateReceivedEvent()
' Create a new instance.
Dim client As New Imap()
AddHandler client.CertificateReceived, AddressOf client_CertificateReceived
' Connect to the IMAP server.
client.Connect("myserver", 143, SslSecurityMode.Explicit)
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
' ...
' Disconnect.
client.Disconnect()
End Sub
''' <summary>
''' Returns all issues of the given certificate.
''' </summary>
''' <param name="status">The certificate verification result.</param>
''' <param name="code">The error code.</param>
''' <returns>Certificate problems.</returns>
Private Shared Function GetCertProblem(ByVal status As CertificateVerificationStatus, ByVal code As Integer) As String
Select Case status
Case CertificateVerificationStatus.TimeNotValid
Return "Server's certificate has expired or is not valid yet."
Case CertificateVerificationStatus.Revoked
Return "Server's certificate has been revoked."
Case CertificateVerificationStatus.UnknownCa
Return "Server's certificate was issued by an unknown authority."
Case CertificateVerificationStatus.UntrustedRoot
Return "Server's certificate was issued by an untrusted authority."
Case CertificateVerificationStatus.IncompleteChain
Return "Server's certificate does not chain up to a trusted root authority."
Case CertificateVerificationStatus.Malformed
Return "Server's certificate is malformed."
Case CertificateVerificationStatus.CnNotMatch
Return "Server hostname does not match the certificate."
Case CertificateVerificationStatus.UnknownError
Return String.Format("Error {0:x} encountered while validating server's certificate.", code)
Case Else
Return status.ToString()
End Select
End Function
Private Sub client_CertificateReceived(ByVal sender As Object, ByVal e As ComponentPro.Security.CertificateReceivedEventArgs)
Dim cert As X509Certificate2 = e.ServerCertificates(0)
Dim status As CertificateVerificationStatus = e.Status
Dim values() As CertificateVerificationStatus = CType(System.Enum.GetValues(GetType(CertificateVerificationStatus)), CertificateVerificationStatus())
Dim sbIssues As New StringBuilder()
For i As Integer = 0 To values.Length - 1
' Matches the validation status?
If (status And values(i)) = 0 Then
Continue For
End If
' The issue is processed.
status = status Xor values(i)
sbIssues.AppendFormat("{0}" & vbCrLf, GetCertProblem(values(i), e.ErrorCode))
Next i
Console.WriteLine("Issue: " & sbIssues.ToString())
Console.WriteLine("Subject: " & cert.SubjectName.Name)
Console.WriteLine("Issuer: " & cert.IssuerName.Name)
Console.WriteLine("Effective Date: " & cert.NotBefore)
Console.WriteLine("Expiry Date: " & cert.NotAfter)
Console.ResetColor()
Console.Write("Do you want to accept this certificate (Add to trusted list, Yes, No) [a,y,n]?")
Dim response As String = Console.ReadLine().Trim().ToLower()
' Add certiticate of the issuer CA to the trusted list.
If response = "a" Then
e.AddToTrustedRoot = True
ElseIf response = "y" Then
e.Accept = True
End If
End Sub
// Create a new instance.
Imap client = new Imap();
// Create a new proxy object.
WebProxyEx proxy = new WebProxyEx();
proxy.Server = "proxyserver"; // Set proxy address here.
proxy.Port = 1080; // Set proxy port here.
proxy.UserName = "username"; // Proxy user name.
proxy.Password = "password"; // Password.
client.Proxy = proxy;
// Connect to the IMAP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
// ...
// Select INBOX mailbox.
client.Select("INBOX");
// Print out unique id of all messages.
foreach (ImapMessage msg in client.ListMessages(ImapEnvelopeParts.UniqueId))
{
Console.WriteLine(msg.UniqueId);
}
// Disconnect.
client.Disconnect();
' Create a new instance.
Dim client As New Imap()
' Create a new proxy object.
Dim proxy As New WebProxyEx()
proxy.Server = "proxyserver" ' Set proxy address here.
proxy.Port = 1080 ' Set proxy port here.
proxy.UserName = "username" ' Proxy user name.
proxy.Password = "password" ' Password.
client.Proxy = proxy
' Connect to the IMAP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
' ...
' Select INBOX mailbox.
client.Select("INBOX")
' Print out unique id of all messages.
For Each msg As ImapMessage In client.ListMessages(ImapEnvelopeParts.UniqueId)
Console.WriteLine(msg.UniqueId)
Next msg
' Disconnect.
client.Disconnect()
The Imap class fully supports many proxy servers (often referred to as "proxies"). If you need to connect to your IMAP server through a proxy, simply create a new instance of the WebProxyEx
class, set the appropriate properties of the WebProxyEx
object, and assign it to the Proxy
property of the Imap
class, and the necessary proxy communication will take place.
The Imap class supports the following Proxy servers:
Proxy | Name |
---|---|
SOCKS4 | SOCKS4 proxy. |
SOCKS4A | SOCKS4A proxy (capable of resolving domain names). |
SOCKS5 | SOCKS5 proxy. |
HTTP CONNECT | HTTP proxy using CONNECT method. |
The Imap class supports many authentication methods including password, NTLM, and client certificates.
To authenticate a user with password-based authentication, use this Authenticate
method overload. The first parameter is the name of the user, and the second one is the user's password.
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the IMAP port with
// client.Connect("myserver", 143);
// Login to the server.
client.Authenticate("user", "password");
StringBuilder sb = new StringBuilder();
FolderCollection list = client.ListFolders();
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].Name);
}
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the IMAP port with
' client.Connect("myserver", 143);
' Login to the server.
client.Authenticate("user", "password")
Dim sb As New StringBuilder()
Dim list As FolderCollection = client.ListFolders()
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).Name)
Next i
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the IMAP port with
// client.Connect("myserver", 143);
// Login to the server using NTLM authentication method.
client.Authenticate("user", "password", ImapAuthenticationMethod.Ntlm);
StringBuilder sb = new StringBuilder();
FolderCollection list = client.ListFolders();
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].Name);
}
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the IMAP port with
' client.Connect("myserver", 143);
' Login to the server using NTLM authentication method.
client.Authenticate("user", "password", ImapAuthenticationMethod.Ntlm)
Dim sb As New StringBuilder()
Dim list As FolderCollection = client.ListFolders()
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).Name)
Next i
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()
To authenticate to an IMAP server using NTLM, specify the enum value ImapAuthenticationMethod.Ntlm
when calling the Authenticate
method.
When connecting to a secure IMAP/SSL server, it may ask the client for a certificate to authenticate the user. To provide a certificate for the authentication, handle the CertificateRequired
event, and provide the certificate in the event handler. There are several ways of doing that:
public void HandleCertificateRequiredEvent()
{
// Create a new instance.
Imap client = new Imap();
client.CertificateRequired += client_CertificateRequired;
// Connect to the IMAP server.
client.Connect("myserver", 143, SslSecurityMode.Explicit);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
// ...
// Disconnect.
client.Disconnect();
}
void client_CertificateRequired(object sender, ComponentPro.Security.CertificateRequiredEventArgs e)
{
// Load certificates from the local machine.
X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
my.Open(OpenFlags.ReadOnly);
// Retrieve a list of available certificates.
X509Certificate2Collection certs = my.Certificates;
// If no certificate found, return.
if (certs.Count == 0)
{
e.Certificates = null;
return;
}
// Show all certificates.
Console.WriteLine("Select certificate:");
for (int i = 0; i <= certs.Count; i++)
{
if (i == 0)
{
Console.WriteLine(string.Format("{0}. [Nothing, skip this step]", i));
continue;
}
Console.WriteLine(string.Format("{0}. {1}", i, certs[i - 1].SubjectName.Name));
}
// And ask user to choose an appropriate certificate.
while (true)
{
Console.Write(string.Format("Select certificate [0 - {0}]: ", certs.Count));
int certIndex;
try
{
certIndex = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("ERROR: Wrong certificate index input!");
continue;
}
if (certIndex > 0 && certIndex <= certs.Count)
{
e.Certificates = new X509Certificate2Collection(certs[certIndex]);
return;
}
if (certIndex == 0)
break;
Console.WriteLine(string.Format("ERROR: You must enter number between 0 and {0}.", certs.Count));
}
}
Public Sub HandleCertificateRequiredEvent()
' Create a new instance.
Dim client As New Imap()
AddHandler client.CertificateRequired, AddressOf client_CertificateRequired
' Connect to the IMAP server.
client.Connect("myserver", 143, SslSecurityMode.Explicit)
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_CertificateRequired(ByVal sender As Object, ByVal e As ComponentPro.Security.CertificateRequiredEventArgs)
' Load certificates from the local machine.
Dim my As New X509Store(StoreName.My, StoreLocation.CurrentUser)
my.Open(OpenFlags.ReadOnly)
' Retrieve a list of available certificates.
Dim certs As X509Certificate2Collection = my.Certificates
' If no certificate found, return.
If certs.Count = 0 Then
e.Certificates = Nothing
Return
End If
' Show all certificates.
Console.WriteLine("Select certificate:")
For i As Integer = 0 To certs.Count
If i = 0 Then
Console.WriteLine(String.Format("{0}. [Nothing, skip this step]", i))
Continue For
End If
Console.WriteLine(String.Format("{0}. {1}", i, certs(i - 1).SubjectName.Name))
Next i
' And ask user to choose an appropriate certificate.
Do
Console.Write(String.Format("Select certificate [0 - {0}]: ", certs.Count))
Dim certIndex As Integer
Try
certIndex = Integer.Parse(Console.ReadLine())
Catch
Console.WriteLine("ERROR: Wrong certificate index input!")
Continue Do
End Try
If certIndex > 0 AndAlso certIndex <= certs.Count Then
e.Certificates = New X509Certificate2Collection(certs(certIndex))
Return
End If
If certIndex = 0 Then
Exit Do
End If
Console.WriteLine(String.Format("ERROR: You must enter number between 0 and {0}.", certs.Count))
Loop
End Sub
You can handle the events in the Imap
class to get notified when an event is triggered.
The CertificateRequired
event is triggered when a client certificate is required by the Imap server, or the one provided was not accepted. For more details, visit topic Authenticate with a client certificate.
public void HandleCertificateRequiredEvent()
{
// Create a new instance.
Imap client = new Imap();
client.CertificateRequired += client_CertificateRequired;
// Connect to the IMAP server.
client.Connect("myserver", 143, SslSecurityMode.Explicit);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
// ...
// Disconnect.
client.Disconnect();
}
void client_CertificateRequired(object sender, ComponentPro.Security.CertificateRequiredEventArgs e)
{
// Load certificates from the local machine.
X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
my.Open(OpenFlags.ReadOnly);
// Retrieve a list of available certificates.
X509Certificate2Collection certs = my.Certificates;
// If no certificate found, return.
if (certs.Count == 0)
{
e.Certificates = null;
return;
}
// Show all certificates.
Console.WriteLine("Select certificate:");
for (int i = 0; i <= certs.Count; i++)
{
if (i == 0)
{
Console.WriteLine(string.Format("{0}. [Nothing, skip this step]", i));
continue;
}
Console.WriteLine(string.Format("{0}. {1}", i, certs[i - 1].SubjectName.Name));
}
// And ask user to choose an appropriate certificate.
while (true)
{
Console.Write(string.Format("Select certificate [0 - {0}]: ", certs.Count));
int certIndex;
try
{
certIndex = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("ERROR: Wrong certificate index input!");
continue;
}
if (certIndex > 0 && certIndex <= certs.Count)
{
e.Certificates = new X509Certificate2Collection(certs[certIndex]);
return;
}
if (certIndex == 0)
break;
Console.WriteLine(string.Format("ERROR: You must enter number between 0 and {0}.", certs.Count));
}
}
Public Sub HandleCertificateRequiredEvent()
' Create a new instance.
Dim client As New Imap()
AddHandler client.CertificateRequired, AddressOf client_CertificateRequired
' Connect to the IMAP server.
client.Connect("myserver", 143, SslSecurityMode.Explicit)
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_CertificateRequired(ByVal sender As Object, ByVal e As ComponentPro.Security.CertificateRequiredEventArgs)
' Load certificates from the local machine.
Dim my As New X509Store(StoreName.My, StoreLocation.CurrentUser)
my.Open(OpenFlags.ReadOnly)
' Retrieve a list of available certificates.
Dim certs As X509Certificate2Collection = my.Certificates
' If no certificate found, return.
If certs.Count = 0 Then
e.Certificates = Nothing
Return
End If
' Show all certificates.
Console.WriteLine("Select certificate:")
For i As Integer = 0 To certs.Count
If i = 0 Then
Console.WriteLine(String.Format("{0}. [Nothing, skip this step]", i))
Continue For
End If
Console.WriteLine(String.Format("{0}. {1}", i, certs(i - 1).SubjectName.Name))
Next i
' And ask user to choose an appropriate certificate.
Do
Console.Write(String.Format("Select certificate [0 - {0}]: ", certs.Count))
Dim certIndex As Integer
Try
certIndex = Integer.Parse(Console.ReadLine())
Catch
Console.WriteLine("ERROR: Wrong certificate index input!")
Continue Do
End Try
If certIndex > 0 AndAlso certIndex <= certs.Count Then
e.Certificates = New X509Certificate2Collection(certs(certIndex))
Return
End If
If certIndex = 0 Then
Exit Do
End If
Console.WriteLine(String.Format("ERROR: You must enter number between 0 and {0}.", certs.Count))
Loop
End Sub
public void HandleCertificateReceivedEvent()
{
// Create a new instance.
Imap client = new Imap();
client.CertificateReceived += client_CertificateReceived;
// Connect to the IMAP server.
client.Connect("myserver", 143, SslSecurityMode.Explicit);
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
// ...
// Disconnect.
client.Disconnect();
}
/// <summary>
/// Returns all issues of the given certificate.
/// </summary>
/// <param name="status">The certificate verification result.</param>
/// <param name="code">The error code.</param>
/// <returns>Certificate problems.</returns>
private static string GetCertProblem(CertificateVerificationStatus status, int code)
{
switch (status)
{
case CertificateVerificationStatus.TimeNotValid:
return "Server's certificate has expired or is not valid yet.";
case CertificateVerificationStatus.Revoked:
return "Server's certificate has been revoked.";
case CertificateVerificationStatus.UnknownCa:
return "Server's certificate was issued by an unknown authority.";
case CertificateVerificationStatus.UntrustedRoot:
return "Server's certificate was issued by an untrusted authority.";
case CertificateVerificationStatus.IncompleteChain:
return "Server's certificate does not chain up to a trusted root authority.";
case CertificateVerificationStatus.Malformed:
return "Server's certificate is malformed.";
case CertificateVerificationStatus.CnNotMatch:
return "Server hostname does not match the certificate.";
case CertificateVerificationStatus.UnknownError:
return string.Format("Error {0:x} encountered while validating server's certificate.", code);
default:
return status.ToString();
}
}
void client_CertificateReceived(object sender, ComponentPro.Security.CertificateReceivedEventArgs e)
{
X509Certificate2 cert = e.ServerCertificates[0];
CertificateVerificationStatus status = e.Status;
CertificateVerificationStatus[] values = (CertificateVerificationStatus[])Enum.GetValues(typeof(CertificateVerificationStatus));
StringBuilder sbIssues = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
// Matches the validation status?
if ((status & values[i]) == 0)
continue;
// The issue is processed.
status ^= values[i];
sbIssues.AppendFormat("{0}\r\n", GetCertProblem(values[i], e.ErrorCode));
}
Console.WriteLine("Issue: " + sbIssues.ToString());
Console.WriteLine("Subject: " + cert.SubjectName.Name);
Console.WriteLine("Issuer: " + cert.IssuerName.Name);
Console.WriteLine("Effective Date: " + cert.NotBefore);
Console.WriteLine("Expiry Date: " + cert.NotAfter);
Console.ResetColor();
Console.Write("Do you want to accept this certificate (Add to trusted list, Yes, No) [a,y,n]?");
string response = Console.ReadLine().Trim().ToLower();
// Add certiticate of the issuer CA to the trusted list.
if (response == "a")
{
e.AddToTrustedRoot = true;
}
else if (response == "y")
{
e.Accept = true;
}
}
Public Sub HandleCertificateReceivedEvent()
' Create a new instance.
Dim client As New Imap()
AddHandler client.CertificateReceived, AddressOf client_CertificateReceived
' Connect to the IMAP server.
client.Connect("myserver", 143, SslSecurityMode.Explicit)
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
' ...
' Disconnect.
client.Disconnect()
End Sub
''' <summary>
''' Returns all issues of the given certificate.
''' </summary>
''' <param name="status">The certificate verification result.</param>
''' <param name="code">The error code.</param>
''' <returns>Certificate problems.</returns>
Private Shared Function GetCertProblem(ByVal status As CertificateVerificationStatus, ByVal code As Integer) As String
Select Case status
Case CertificateVerificationStatus.TimeNotValid
Return "Server's certificate has expired or is not valid yet."
Case CertificateVerificationStatus.Revoked
Return "Server's certificate has been revoked."
Case CertificateVerificationStatus.UnknownCa
Return "Server's certificate was issued by an unknown authority."
Case CertificateVerificationStatus.UntrustedRoot
Return "Server's certificate was issued by an untrusted authority."
Case CertificateVerificationStatus.IncompleteChain
Return "Server's certificate does not chain up to a trusted root authority."
Case CertificateVerificationStatus.Malformed
Return "Server's certificate is malformed."
Case CertificateVerificationStatus.CnNotMatch
Return "Server hostname does not match the certificate."
Case CertificateVerificationStatus.UnknownError
Return String.Format("Error {0:x} encountered while validating server's certificate.", code)
Case Else
Return status.ToString()
End Select
End Function
Private Sub client_CertificateReceived(ByVal sender As Object, ByVal e As ComponentPro.Security.CertificateReceivedEventArgs)
Dim cert As X509Certificate2 = e.ServerCertificates(0)
Dim status As CertificateVerificationStatus = e.Status
Dim values() As CertificateVerificationStatus = CType(System.Enum.GetValues(GetType(CertificateVerificationStatus)), CertificateVerificationStatus())
Dim sbIssues As New StringBuilder()
For i As Integer = 0 To values.Length - 1
' Matches the validation status?
If (status And values(i)) = 0 Then
Continue For
End If
' The issue is processed.
status = status Xor values(i)
sbIssues.AppendFormat("{0}" & vbCrLf, GetCertProblem(values(i), e.ErrorCode))
Next i
Console.WriteLine("Issue: " & sbIssues.ToString())
Console.WriteLine("Subject: " & cert.SubjectName.Name)
Console.WriteLine("Issuer: " & cert.IssuerName.Name)
Console.WriteLine("Effective Date: " & cert.NotBefore)
Console.WriteLine("Expiry Date: " & cert.NotAfter)
Console.ResetColor()
Console.Write("Do you want to accept this certificate (Add to trusted list, Yes, No) [a,y,n]?")
Dim response As String = Console.ReadLine().Trim().ToLower()
' Add certiticate of the issuer CA to the trusted list.
If response = "a" Then
e.AddToTrustedRoot = True
ElseIf response = "y" Then
e.Accept = True
End If
End Sub
The CertificateReceived
event is triggered when Ultimate Mail's Imap class has received the server's certificate. For more details, visit topic Verifying server's certificate.
Progress
event is triggered when a block of data has been sent or received. By handling this event, you can display transfer progress information, source file name, destination file name, etc.
public void ShowProgress()
{
// Create a new Imap instance.
Imap client = new Imap();
// Connect to the IMAP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("test", "test");
try
{
// Register an event handler.
client.Progress += client_Progress;
client.Select("INBOX");
// Download a message with sequence number #1.
client.DownloadMessage(1, "c:\\temp\\my message.eml");
}
catch (ImapException exc)
{
Console.WriteLine("Exception: " + exc.Message);
}
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, ImapProgressEventArgs e)
{
// Show progress information.
if (e.Length > 0 && e.State == ImapTransferState.Downloading)
{
Console.Write("\rDownloaded: {0} bytes ({1}% completed)", e.BytesTransferred, e.Percentage);
}
}
Public Sub ShowProgress()
' Create a new Imap instance.
Dim client As New Imap()
' Connect to the IMAP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("test", "test")
Try
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
client.Select("INBOX")
' Download a message with sequence number #1.
client.DownloadMessage(1, "c:\temp\my message.eml")
Catch exc As ImapException
Console.WriteLine("Exception: " & exc.Message)
End Try
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As ImapProgressEventArgs)
' Show progress information.
If e.Length > 0 AndAlso e.State = ImapTransferState.Downloading Then
Console.Write(vbCr & "Downloaded: {0} bytes ({1}% completed)", e.BytesTransferred, e.Percentage)
End If
End Sub
public void HandleCommandSentResponseReadEvents()
{
// Create a new instance.
Imap client = new Imap();
// Register event handlers.
client.CommandResponse += client_CommandResponse;
// Connect to the IMAP server.
client.Connect("server");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Do something here
// ...
StringBuilder sb = new StringBuilder();
FolderCollection list = client.ListFolders();
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].Name);
}
Console.WriteLine(sb.ToString());
// ...
// Disconnect.
client.Disconnect();
}
void client_CommandResponse(object sender, CommandResponseEventArgs e)
{
if (e.Command != null)
Console.WriteLine("CMD> " + e.Command);
else
Console.WriteLine("RESPONSE> " + e.Response);
}
Public Sub HandleCommandSentResponseReadEvents()
' Create a new instance.
Dim client As New Imap()
' Register event handlers.
AddHandler client.CommandResponse, AddressOf client_CommandResponse
' Connect to the IMAP server.
client.Connect("server")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Do something here
' ...
Dim sb As New StringBuilder()
Dim list As FolderCollection = client.ListFolders()
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).Name)
Next i
Console.WriteLine(sb.ToString())
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_CommandResponse(ByVal sender As Object, ByVal e As CommandResponseEventArgs)
If e.Command IsNot Nothing Then
Console.WriteLine("CMD> " & e.Command)
Else
Console.WriteLine("RESPONSE> " & e.Response)
End If
End Sub
The CommandResponse
event is triggered when a command has been sent to the IMAP server or when Mail component has received a response from the server. This event is commonly used to add trace log capabilities to your applications. For more details on how to handle this event, visit Making a trace log using events. There is still another convenient way to add log capabilities to your application is using the XTrace class.
The StateChanged
event is triggered when the state of the Imap
object has been changed. By handling this event, you will get a notification when a connection has been established or the connection has been lost.
public void HandleStateChangedEvent()
{
// Create a new instance.
Imap client = new Imap();
client.StateChanged += client_StateChanged;
// Connect to the IMAP server.
client.Connect("server");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Do something here
// ...
// Disconnect.
client.Disconnect();
}
void client_StateChanged(object sender, ImapStateChangedEventArgs e)
{
Console.WriteLine("State changed, old state: {0}, new state: {1}", e.OldState, e.State);
}
Public Sub HandleStateChangedEvent()
' Create a new instance.
Dim client As New Imap()
AddHandler client.StateChanged, AddressOf client_StateChanged
' Connect to the IMAP server.
client.Connect("server")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Do something here
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_StateChanged(ByVal sender As Object, ByVal e As ImapStateChangedEventArgs)
Console.WriteLine("State changed, old state: {0}, new state: {1}", e.OldState, e.State)
End Sub
public void HandleUpdateEvent()
{
// Create a new instance.
Imap client = new Imap();
client.Update += client_Update;
// Connect to the IMAP server.
client.Connect("server");
// Authenticate.
client.Authenticate("test", "test");
// ...
while (!quit)
{
// Check for updates every 1 min.
client.CheckForUpdates();
System.Threading.Thread.Sleep(60 * 1000); // Sleep 1 min.
// ...
}
// ...
// Disconnect.
client.Disconnect();
}
void client_Update(object sender, ImapUpdateEventArgs e)
{
Console.WriteLine("New event: " + e.Event);
}
Public Sub HandleUpdateEvent()
' Create a new instance.
Dim client As New Imap()
AddHandler client.Update, AddressOf client_Update
' Connect to the IMAP server.
client.Connect("server")
' Authenticate.
client.Authenticate("test", "test")
' ...
Do While Not quit
' Check for updates every 1 min.
client.CheckForUpdates()
System.Threading.Thread.Sleep(60 * 1000) ' Sleep 1 min.
' ...
Loop
' ...
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Update(ByVal sender As Object, ByVal e As ImapUpdateEventArgs)
Console.WriteLine("New event: " & e.Event)
End Sub
The Update event is fired when a new message has arrived, message flags have changed, an error has occurred, etc. You can use the CheckForUpdates method to send a NOOP or IDLE command to the server to check for any updates from the server.
The following steps guide you on how to handle this event.
IMAP folders let you categorize your messages. The Imap class helps you manage them with intuitive APIs.
The simplest way to obtain information about a folder is by using GetFolderInfo
method. You only need to pass the folder name to the method. It returns a Folder object containing information about the folder you have requested.
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the IMAP port with
// client.Connect("myserver", 143);
// Login to the server.
client.Authenticate("user", "password");
// Get information about the INBOX mailbox.
Folder m = client.GetFolderInfo("INBOX");
Console.WriteLine("The number of recent messages: " + m.RecentMessages);
Console.WriteLine("The number of new unseen messages messages: " + m.NewUnseenMessages);
// Close the connection.
client.Disconnect();
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the IMAP port with
' client.Connect("myserver", 143);
' Login to the server.
client.Authenticate("user", "password")
' Get information about the INBOX mailbox.
Dim m As Folder = client.GetFolderInfo("INBOX")
Console.WriteLine("The number of recent messages: " & m.RecentMessages)
Console.WriteLine("The number of new unseen messages messages: " & m.NewUnseenMessages)
' Close the connection.
client.Disconnect()
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
StringBuilder sb = new StringBuilder();
FolderCollection list = client.ListFolders();
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].Name);
}
// Show the folder list
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
Dim sb As New StringBuilder()
Dim list As FolderCollection = client.ListFolders()
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).Name)
Next i
' Show the folder list
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()
The simplest way to list mailboxes under the current working mailbox is using ListFolders method. You only need to pass the name of the mailbox to list to the method. If the parameter is empty, mailboxes under the root mailbox will be listed. It returns a collection of Folder object containing information about the mailbox you have requested.
It is effortless to get a list of messages in a folder. To do that, call the ListMessages
method. You can pass an optional ImapEnvelopeParts
parameter indicating which part of the message will be retrieved. Before calling these methods, please make sure you have selected a folder as your current working folder. The ListMessages
method returns a collection of ImapMessage
object containing information about messages you have requested.
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
ImapMessageCollection listMessages = client.ListMessages();
foreach (ImapMessage m in listMessages)
{
Console.WriteLine(string.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size));
}
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
Dim listMessages As ImapMessageCollection = client.ListMessages()
For Each m As ImapMessage In listMessages
Console.WriteLine(String.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size))
Next m
' Close the connection.
client.Disconnect()
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
ImapMessageCollection listMessages = client.ListMessages();
foreach (ImapMessage m in listMessages)
{
Console.WriteLine(string.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size));
}
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
Dim listMessages As ImapMessageCollection = client.ListMessages()
For Each m As ImapMessage In listMessages
Console.WriteLine(String.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size))
Next m
' Close the connection.
client.Disconnect()
By default, after you have successfully logged in with the Connect
/ConnectAsync
and Authenticate
/AuthenticateAsync
methods, the Imap
class does not select any folder. Therefore, before doing any operations related to folders or messages, you are advised to select a folder as your current working one. For example, before listing messages, you have to select a folder (i.e, INBOX). If no folder has been selected, it throws an exception.
To select a folder as a current working one, use the Select method. You only need to pass the folder name to the method. If you wish to deselect the current working folder, call Deselect
method.
As you might know, before doing any operation related to mail messages, you are advised to select a working mailbox using the Select
method. When you want to deselect it, call the Deselect
method. After calling this method, no current working mailbox is specified.
The following steps will help you to do that:
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
ImapMessageCollection listMessages = client.ListMessages();
foreach (ImapMessage m in listMessages)
{
Console.WriteLine(string.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size));
}
// Now deselect the current working mailbox.
client.Deselect();
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
Dim listMessages As ImapMessageCollection = client.ListMessages()
For Each m As ImapMessage In listMessages
Console.WriteLine(String.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size))
Next m
' Now deselect the current working mailbox.
client.Deselect()
' Close the connection.
client.Disconnect()
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Create a new mailbox named 'My Mybox' in the root folder.
client.CreateFolder("My Mailbox");
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Create a new mailbox named 'My Mybox' in the root folder.
client.CreateFolder("My Mailbox")
' Close the connection.
client.Disconnect()
An important aspect of the IMAP protocol is the concept of folders. Folders on the server are used to "organize" messages in a way that is functionally equivalent to local folders. Imap class provides a number of convenient methods to work with Imap folder such as CreateFolder, DeleteFolder, GetFolderInfo, ListFolders, Select, and Deselect.
To create a new mailbox, call the CreateFolder method. You only need to pass the mailbox name to the method.
The simplest way to delete a folder is by using the DeleteFolder method. You only need to pass the folder name to the method.
The following steps will help you to do that:
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Delete a 'My Mybox' folder in the root folder.
client.DeleteFolder("My Mailbox");
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Delete a 'My Mybox' folder in the root folder.
client.DeleteFolder("My Mailbox")
' Close the connection.
client.Disconnect()
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the IMAP port with
// client.Connect("myserver", 143);
// Login to the server.
client.Authenticate("user", "password");
// Check to see whether the mailbox 'my mailbox' exists or not.
bool result = client.FolderExists("my mailbox");
if (result)
Console.WriteLine("Mailbox exists");
else
Console.WriteLine("Mailbox does not exists");
// Close the connection.
client.Disconnect();
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the IMAP port with
' client.Connect("myserver", 143);
' Login to the server.
client.Authenticate("user", "password")
' Check to see whether the mailbox 'my mailbox' exists or not.
Dim result As Boolean = client.FolderExists("my mailbox")
If result Then
Console.WriteLine("Mailbox exists")
Else
Console.WriteLine("Mailbox does not exists")
End If
' Close the connection.
client.Disconnect()
To determine whether a folder exists or not, call the FolderExists method. You only need to pass the mailbox name to the method. It returns a boolean value indicating whether the mailbox exists or not.
The Imap class also has a comprehensive API to manage mail messages.
To download unread messages, you will need to call the ListMessages with ImapCriterion.DontHaveFlags(ImapMessageFlags.Seen)
. The following code takes advantage of the method to download all unread messages from an IMAP account:
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox
client.Select("INBOX");
// Get the message list.
Console.WriteLine("Getting message list...");
ImapMessageCollection list = client.ListMessages(ImapEnvelopeParts.UniqueId | ImapEnvelopeParts.Size, ImapCriterion.DontHaveFlags(ImapMessageFlags.Seen));
// Get messages.
for (int i = 0; i < list.Count; i++)
{
ImapMessage imapMessage = list[i];
// Download the message to an instance of the MailMessage class.
MailMessage msg = client.DownloadMailMessage(imapMessage.UniqueId);
// Display some information about it.
Console.WriteLine("Size: " + imapMessage.Size);
Console.WriteLine("Number of attachments: " + msg.Attachments.Count);
Console.WriteLine("Number of header name value pairs: " + msg.Headers.Count);
}
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox
client.Select("INBOX")
' Get the message list.
Console.WriteLine("Getting message list...")
Dim list As ImapMessageCollection = client.ListMessages(ImapEnvelopeParts.UniqueId Or ImapEnvelopeParts.Size, ImapCriterion.DontHaveFlags(ImapMessageFlags.Seen))
' Get messages.
For i As Integer = 0 To list.Count - 1
Dim imapMessage As ImapMessage = list(i)
' Download the message to an instance of the MailMessage class.
Dim msg As MailMessage = client.DownloadMailMessage(imapMessage.UniqueId)
' Display some information about it.
Console.WriteLine("Size: " & imapMessage.Size)
Console.WriteLine("Number of attachments: " & msg.Attachments.Count)
Console.WriteLine("Number of header name value pairs: " & msg.Headers.Count)
Next i
' Close the connection.
client.Disconnect()
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox
client.Select("INBOX");
// Get the message list.
Console.WriteLine("Getting message list...");
ImapMessageCollection list = client.ListMessages(ImapEnvelopeParts.UniqueId | ImapEnvelopeParts.Size);
// Get messages.
for (int i = 0; i < list.Count; i++)
{
ImapMessage imapMessage = list[i];
// Download the message to an instance of the MailMessage class.
MailMessage msg = client.DownloadMailMessage(imapMessage.UniqueId);
// It can be downloaded with the sequence number.
// MailMessage msg = client.DownloadMailMessage(imapMessage.SequenceNumber);
// Display some information about it.
Console.WriteLine("Size: " + imapMessage.Size);
Console.WriteLine("Number of attachments: " + msg.Attachments.Count);
Console.WriteLine("Number of header name value pairs: " + msg.Headers.Count);
}
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox
client.Select("INBOX")
' Get the message list.
Console.WriteLine("Getting message list...")
Dim list As ImapMessageCollection = client.ListMessages(ImapEnvelopeParts.UniqueId Or ImapEnvelopeParts.Size)
' Get messages.
For i As Integer = 0 To list.Count - 1
Dim imapMessage As ImapMessage = list(i)
' Download the message to an instance of the MailMessage class.
Dim msg As MailMessage = client.DownloadMailMessage(imapMessage.UniqueId)
' It can be downloaded with the sequence number.
' MailMessage msg = client.DownloadMailMessage(imapMessage.SequenceNumber);
' Display some information about it.
Console.WriteLine("Size: " & imapMessage.Size)
Console.WriteLine("Number of attachments: " & msg.Attachments.Count)
Console.WriteLine("Number of header name value pairs: " & msg.Headers.Count)
Next i
' Close the connection.
client.Disconnect()
Downloading mail messages from an IMAP server in UltimateMail component is so simple, you call the DownloadMailMessage
method, and you retrieve an instance of the MailMessage class. You can now read, modify, save to disk the message. If you need to download the message to disk or write it into a stream, call the convenient DownloadMessage
method instead.
The example below shows you how to get a list of messages from an IMAP server and download and save all messages to disk:
You can either retrieve a message as an instance of the MailMessage class or download it as a raw EML message to disk or write it into a data stream with DownloadMessage method.
The following steps will help you to do that:
static void Main()
{
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox
client.Select("INBOX");
// Get the message list.
Console.WriteLine("Getting message list...");
ImapMessageCollection list = client.ListMessages(ImapEnvelopeParts.UniqueId);
// Get messages.
for (int i = 0; i < list.Count; i++)
{
ImapMessage message = list[i];
// Get file name.
string filename = GetFilename(message.UniqueId) + ".eml";
// Get new message only.
if (!System.IO.File.Exists(filename))
{
Console.WriteLine("Downloading message {0}...", message.UniqueId);
client.DownloadMessage(message.UniqueId, filename);
}
}
// Close the connection.
client.Disconnect();
}
/// <summary>
/// Returns a uniquely correct file name from the specified unique message ID.
/// </summary>
/// <param name="uniqueId">The unique id.</param>
/// <returns>The corrected file name.</returns>
private static string GetFilename(string uniqueId)
{
// Characters allowed in the filename
const string allowed = " .-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Replace invalid charactes with its hex representation
StringBuilder sb = new StringBuilder();
for (int i = 0; i < uniqueId.Length; i++)
{
if (allowed.IndexOf(uniqueId[i]) < 0)
sb.AppendFormat("_{0:X2}", (int)uniqueId[i]);
else
sb.Append(uniqueId[i]);
}
return sb.ToString();
}
Shared Sub Main()
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox
client.Select("INBOX")
' Get the message list.
Console.WriteLine("Getting message list...")
Dim list As ImapMessageCollection = client.ListMessages(ImapEnvelopeParts.UniqueId)
' Get messages.
For i As Integer = 0 To list.Count - 1
Dim message As ImapMessage = list(i)
' Get file name.
Dim filename As String = GetFilename(message.UniqueId) & ".eml"
' Get new message only.
If Not System.IO.File.Exists(filename) Then
Console.WriteLine("Downloading message {0}...", message.UniqueId)
client.DownloadMessage(message.UniqueId, filename)
End If
Next i
' Close the connection.
client.Disconnect()
End Sub
''' <summary>
''' Returns a uniquely correct file name from the specified unique message ID.
''' </summary>
''' <param name="uniqueId">The unique id.</param>
''' <returns>The corrected file name.</returns>
Private Shared Function GetFilename(ByVal uniqueId As String) As String
' Characters allowed in the filename
Const allowed As String = " .-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
' Replace invalid charactes with its hex representation
Dim sb As New StringBuilder()
For i As Integer = 0 To uniqueId.Length - 1
If allowed.IndexOf(uniqueId.Chars(i)) < 0 Then
sb.AppendFormat("_{0:X2}", System.Convert.ToInt32(uniqueId.Chars(i)))
Else
sb.Append(uniqueId.Chars(i))
End If
Next i
Return sb.ToString()
End Function
// Example Title : Download headers of messages
// Example Description : Shows how to connect to an IMAP server and download headers of messages.
// Example Group : Imap Message
using System;
using System.IO;
using ComponentPro.Net;
using ComponentPro.Net.Mail;
namespace Samples.ImapExample
{
class DownloadMessageHeaders
{
[STAThread]
static void Main()
{
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "password";
const int port = 993;
const string folder = "Inbox";
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
Imap client = new Imap();
try
{
Console.WriteLine("Connecting IMAP server: {0}:{1}...", serverName, port);
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
Console.WriteLine("Logging in as {0}...", user);
client.Authenticate(user, password);
// Select working folder.
Console.WriteLine("Selecting folder '{0}'...", folder);
client.Select(folder);
Folder workingFolder = client.WorkingFolder;
// Show the number of messages in the selected folder.
Console.WriteLine("{0} messages found.", workingFolder.TotalMessages);
// Get the message list.
Console.WriteLine("Getting message list...");
ImapMessageCollection list = client.ListMessages(ImapEnvelopeParts.FullHeaders);
ImapMessage message;
for (int i = 0; i < list.Count; i++)
{
message = list[i];
// Print out message uniqueid and sequence id
Console.WriteLine("UniqueId: {0}, Sequence Num: {1}", message.UniqueId, message.MessageInboxIndex);
Console.WriteLine("From: {0}, To: {1}, Subject: '{2}'", message.From, message.To, message.Subject);
Console.WriteLine();
}
// Get the message list.
Console.WriteLine("Getting message list...");
list = client.ListMessages(ImapEnvelopeParts.MessageInboxIndex);
for (int i = 0; i < list.Count; i++)
{
message = list[i];
// Download message headers to a stream.
Stream s = new MemoryStream();
client.DownloadMessageHeaders(message.MessageInboxIndex, s);
// Load message from the Stream object.
MailMessage msg = new MailMessage(s);
// Print out message uniqueid and sequence id
Console.WriteLine("Sequence Num: {0}", message.MessageInboxIndex);
Console.WriteLine("From: {0}, To: {1}, Subject: '{2}'", msg.From, msg.To, msg.Subject);
Console.WriteLine();
}
// Disconnect.
Console.WriteLine("Disconnecting...");
client.Disconnect();
}
catch (ImapException imapExc)
{
Console.WriteLine(string.Format("An IMAP error occurred: {0}, ErrorStatus: {1}", imapExc.Message, imapExc.Status));
}
catch (Exception exc)
{
Console.WriteLine(string.Format("An error occurred: {0}", exc.Message));
}
}
}
}
' Example Title : Download headers of messages
' Example Description : Shows how to connect to an IMAP server and download headers of messages.
' Example Group : Imap Message
Imports System.IO
Imports ComponentPro.Net
Imports ComponentPro.Net.Mail
Namespace Samples.ImapExample
Friend Class DownloadMessageHeaders
<STAThread> _
Shared Sub Main()
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "password"
Const port As Integer = 993
Const folder As String = "Inbox"
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
Dim client As New Imap()
Try
Console.WriteLine("Connecting IMAP server: {0}:{1}...", serverName, port)
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
Console.WriteLine("Logging in as {0}...", user)
client.Authenticate(user, password)
' Select working folder.
Console.WriteLine("Selecting folder '{0}'...", folder)
client.Select(folder)
Dim workingFolder As Folder = client.WorkingFolder
' Show the number of messages in the selected folder.
Console.WriteLine("{0} messages found.", workingFolder.TotalMessages)
' Get the message list.
Console.WriteLine("Getting message list...")
Dim list As ImapMessageCollection = client.ListMessages(ImapEnvelopeParts.FullHeaders)
Dim message As ImapMessage
For i As Integer = 0 To list.Count - 1
message = list(i)
' Print out message uniqueid and sequence id
Console.WriteLine("UniqueId: {0}, Sequence Num: {1}", message.UniqueId, message.MessageInboxIndex)
Console.WriteLine("From: {0}, To: {1}, Subject: '{2}'", message.From, message.To, message.Subject)
Console.WriteLine()
Next i
' Get the message list.
Console.WriteLine("Getting message list...")
list = client.ListMessages(ImapEnvelopeParts.MessageInboxIndex)
For i As Integer = 0 To list.Count - 1
message = list(i)
' Download message headers to a stream.
Dim s As Stream = New MemoryStream()
client.DownloadMessageHeaders(message.MessageInboxIndex, s)
' Load message from the Stream object.
Dim msg As New MailMessage(s)
' Print out message uniqueid and sequence id
Console.WriteLine("Sequence Num: {0}", message.MessageInboxIndex)
Console.WriteLine("From: {0}, To: {1}, Subject: '{2}'", msg.From, msg.To, msg.Subject)
Console.WriteLine()
Next i
' Disconnect.
Console.WriteLine("Disconnecting...")
client.Disconnect()
Catch imapExc As ImapException
Console.WriteLine(String.Format("An IMAP error occurred: {0}, ErrorStatus: {1}", imapExc.Message, imapExc.Status))
Catch exc As Exception
Console.WriteLine(String.Format("An error occurred: {0}", exc.Message))
End Try
End Sub
End Class
End Namespace
You can retrieve all message headers by simply calling the ListMessages with parameter ImapEnvelopeParts.FullHeaders. However, this might take a very long time if the mailbox contains a lot of messages or the bandwidth is limited. We will take advantage of the DownloadMessageHeaders method by the following example:
IMAP also allows you to upload message from a client to a folder on an IMAP server, and Imap class provides the UploadMessage method for this purpose. By using the UploadMessage method, you can upload message from a various source such as from file, stream, or MailMessage object. Unlike other message-related methods, the UploadMessage method uploads the message into a specified folder, so that the current folder is not used for the operation, and you do not need to set the current folder before using the UploadMessage method.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "password";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
Imap client = new Imap();
try
{
Console.WriteLine("Connecting IMAP server: {0}:{1}...", serverName, port);
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
Console.WriteLine("Logging in as {0}...", user);
client.Authenticate(user, password);
// Create a new MailMessage object.
MailMessage message = new MailMessage();
message.From.Add("from@thedomain.com");
message.To.Add("name@domain.com");
message.Subject = "Test Subject";
message.BodyText = "Test Content";
// Upload message.
Console.WriteLine("Uploading message...");
// Upload the message to the 'Inbox' mailbox.
client.UploadMessage("Inbox", message);
// Disconnect.
Console.WriteLine("Disconnecting...");
client.Disconnect();
}
catch (ImapException imapExc)
{
Console.WriteLine(string.Format("An IMAP error occurred: {0}, ErrorStatus: {1}", imapExc.Message, imapExc.Status));
}
catch (Exception exc)
{
Console.WriteLine(string.Format("An error occurred: {0}", exc.Message));
}
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "password"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
Dim client As New Imap()
Try
Console.WriteLine("Connecting IMAP server: {0}:{1}...", serverName, port)
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
Console.WriteLine("Logging in as {0}...", user)
client.Authenticate(user, password)
' Create a new MailMessage object.
Dim message As New MailMessage()
message.From.Add("from@thedomain.com")
message.To.Add("name@domain.com")
message.Subject = "Test Subject"
message.BodyText = "Test Content"
' Upload message.
Console.WriteLine("Uploading message...")
' Upload the message to the 'Inbox' mailbox.
client.UploadMessage("Inbox", message)
' Disconnect.
Console.WriteLine("Disconnecting...")
client.Disconnect()
Catch imapExc As ImapException
Console.WriteLine(String.Format("An IMAP error occurred: {0}, ErrorStatus: {1}", imapExc.Message, imapExc.Status))
Catch exc As Exception
Console.WriteLine(String.Format("An error occurred: {0}", exc.Message))
End Try
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
// Copy a message with sequence # 1 to 'my mailbox' folder.
client.CopyMessage(1, "my mailbox");
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
' Copy a message with sequence # 1 to 'my mailbox' folder.
client.CopyMessage(1, "my mailbox")
' Close the connection.
client.Disconnect()
The simplest way to copy a message from the current working mailbox to another mailbox is using the CopyMessage method. You can either pass the message's sequence number or unique id to the method.
The simplest way to copy multiple messages from the current working mailbox to another mailbox is using the CopyMessage method. You need to create a new instance of the message id list class - ImapMessageIdCollection and add sequence numbers or unique ids of the messages you want to copy.
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
ImapMessageIdCollection set = new ImapMessageIdCollection(1, 2, 3);
// Copy mail messages with sequence numbers 1, 2, and 3 to folder 'my box'.
client.CopyMessage(set, "my box");
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
Dim [set] As New ImapMessageIdCollection(1, 2, 3)
' Copy mail messages with sequence numbers 1, 2, and 3 to folder 'my box'.
client.CopyMessage([set], "my box")
' Close the connection.
client.Disconnect()
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
// Move a message with sequence # 1 to 'my mailbox' folder.
client.MoveMessage(1, "my mailbox");
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
' Move a message with sequence # 1 to 'my mailbox' folder.
client.MoveMessage(1, "my mailbox")
' Close the connection.
client.Disconnect()
To move one or more messages in the current working mailbox to another mailbox, call the MoveMessage method. If you are going to move a single message, you can either pass the message sequence number of unique id and the destination mailbox name to the method. If you wish to move more than one messages, create a new instance of the message id list class - ImapMessageIdCollection and add sequence numbers or unique ids of the messages you want to move.
Imap class provides two methods DeleteMessage for deleting messages and UndeleteMessage for undeleting messages.
You use the DeleteMessage method to mark a message as deleted. It won't appear in subsequent message lists, but will only be removed from the mailbox after a call to the Purge
method, the current mailbox is changed using Select, or the session is disconnected using Disconnect method. You can recover messages that were marked as deleted by using the UndeleteMessage method.
The following steps will help you to delete a single message using the DeleteMessage method:
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
// Delete a mail message with inbox index 1.
client.DeleteMessage(1);
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
' Delete a mail message with inbox index 1.
client.DeleteMessage(1)
' Close the connection.
client.Disconnect()
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
ImapMessageIdCollection set = new ImapMessageIdCollection(1, 2, 3);
// Delete mail messages with sequence numbers 1, 2, and 3.
client.DeleteMessage(set);
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
Dim [set] As New ImapMessageIdCollection(1, 2, 3)
' Delete mail messages with sequence numbers 1, 2, and 3.
client.DeleteMessage([set])
' Close the connection.
client.Disconnect()
The following steps will help you to delete multiple messages using the DeleteMessage method:
To purge all messages marked as deleted from the current folder, you can either call Purge or Deselect(true) methods.
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox
client.Select("INBOX");
// Delete a message with Sequence number # 1.
client.DeleteMessage(1);
// ...
// Purge all messages marked as deleted in the 'INBOX' mailbox
client.Purge();
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox
client.Select("INBOX")
' Delete a message with Sequence number # 1.
client.DeleteMessage(1)
' ...
' Purge all messages marked as deleted in the 'INBOX' mailbox
client.Purge()
' Close the connection.
client.Disconnect()
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
ImapMessageIdCollection set = new ImapMessageIdCollection(1, 2, 3);
// Delete mail messages with sequence numbers 1, 2, and 3.
client.DeleteMessage(set);
// ...
// Undelete messages.
client.UndeleteMessage(set);
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
Dim [set] As New ImapMessageIdCollection(1, 2, 3)
' Delete mail messages with sequence numbers 1, 2, and 3.
client.DeleteMessage([set])
' ...
' Undelete messages.
client.UndeleteMessage([set])
' Close the connection.
client.Disconnect()
Imap class provides two methods DeleteMessage for deleting messages and UndeleteMessage for undeleting messages.
You use the DeleteMessage method to mark a message as deleted. It won't appear in subsequent message lists, but will only be removed from the mailbox after a call to Purge method, the current mailbox is changed using Select, or the session is disconnected using Disconnect method. You can recover messages that were marked as deleted by using the UndeleteMessage method.
IMAP defines some message flags such as "Answered", "Deleted", "Draft", "Seen". Most of them can be changed. Only the "Recent" flag is read-only, the flag indicates that the message has recently arrived and it is the first and only session notified about the message. You can use the response returned from the ListMessages method to get the message flags.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "password";
const int port = 993;
const string folder = "Inbox";
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
Imap client = new Imap();
try
{
Console.WriteLine("Connecting IMAP server: {0}:{1}...", serverName, port);
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
Console.WriteLine("Logging in as {0}...", user);
client.Authenticate(user, password);
// Select working folder.
Console.WriteLine("Selecting folder '{0}'...", folder);
client.Select(folder);
// Set the first message in the Inbox as Read.
Console.WriteLine("Selecting the first message as Read...");
client.Flag(1, ImapFlagModifier.Add, ImapMessageFlags.Seen);
// Set the first message in the Inbox as Deleted.
// Setting the "Deleted" flag is equivalent to client.Delete method.
Console.WriteLine("Selecting the first message as Deleted...");
client.Flag(1, ImapFlagModifier.Add, ImapMessageFlags.Deleted);
// Disconnect.
Console.WriteLine("Disconnecting...");
client.Disconnect();
}
catch (ImapException imapExc)
{
Console.WriteLine(string.Format("An IMAP error occurred: {0}, ErrorStatus: {1}", imapExc.Message, imapExc.Status));
}
catch (Exception exc)
{
Console.WriteLine(string.Format("An error occurred: {0}", exc.Message));
}
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "password"
Const port As Integer = 993
Const folder As String = "Inbox"
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
Dim client As New Imap()
Try
Console.WriteLine("Connecting IMAP server: {0}:{1}...", serverName, port)
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
Console.WriteLine("Logging in as {0}...", user)
client.Authenticate(user, password)
' Select working folder.
Console.WriteLine("Selecting folder '{0}'...", folder)
client.Select(folder)
' Set the first message in the Inbox as Read.
Console.WriteLine("Selecting the first message as Read...")
client.Flag(1, ImapFlagModifier.Add, ImapMessageFlags.Seen)
' Set the first message in the Inbox as Deleted.
' Setting the "Deleted" flag is equivalent to client.Delete method.
Console.WriteLine("Selecting the first message as Deleted...")
client.Flag(1, ImapFlagModifier.Add, ImapMessageFlags.Deleted)
' Disconnect.
Console.WriteLine("Disconnecting...")
client.Disconnect()
Catch imapExc As ImapException
Console.WriteLine(String.Format("An IMAP error occurred: {0}, ErrorStatus: {1}", imapExc.Message, imapExc.Status))
Catch exc As Exception
Console.WriteLine(String.Format("An error occurred: {0}", exc.Message))
End Try
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
// Search for messages that have arrived since yesterday.
ImapCriterion criteria = ImapCriterion.ArrivedBetween(DateTime.Now.AddDays(-1), DateTime.Now);
// Search message that match the specified criteria. Only get message's unique Id and Size.
ImapMessageCollection listMessages = client.ListMessages(ImapEnvelopeParts.UniqueId | ImapEnvelopeParts.Size, criteria);
foreach (ImapMessage m in listMessages)
{
Console.WriteLine(string.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size));
}
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
' Search for messages that have arrived since yesterday.
Dim criteria As ImapCriterion = ImapCriterion.ArrivedBetween(Date.Now.AddDays(-1), Date.Now)
' Search message that match the specified criteria. Only get message's unique Id and Size.
Dim listMessages As ImapMessageCollection = client.ListMessages(ImapEnvelopeParts.UniqueId Or ImapEnvelopeParts.Size, criteria)
For Each m As ImapMessage In listMessages
Console.WriteLine(String.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size))
Next m
' Close the connection.
client.Disconnect()
IMAP supports a quite powerful search command. Imap class encapsulated the command into an easy-to-use method called ListMessages, which give you the ability to search for messages matching given criteria.
The following steps will show you how to search for messages that match specified criteria:
The library also comes with some advanced features below:
Imap
provides several methods allowing you to connect, log in, upload, download, etc asynchronously. Their names always end with Async. An async method begins some operation on a new thread and immediately return to the caller. When the operation has completed, the corresponding event will be raised notifying you that the operation has completed and in the event handler method, you can check for the error and use the result, if provided.
The example following demonstrates how to connect to an IMAP server and list messages in INBOX folder asynchronously:
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the IMAP port with
// client.Connect("myserver", 143);
// Login to the server.
client.Authenticate("user", "password");
// ...
// Select 'INBOX' mailbox.
client.Select("INBOX");
// List all messages in the selected folder.
ImapMessageCollection listMessages = await client.ListMessagesAsync();
// ...
foreach (ImapMessage m in listMessages)
{
Console.WriteLine(string.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size));
}
// Disconnect.
client.Disconnect();
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the IMAP port with
' client.Connect("myserver", 143);
' Login to the server.
client.Authenticate("user", "password")
' ...
' Select 'INBOX' mailbox.
client.Select("INBOX")
' List all messages in the selected folder.
Dim listMessages As ImapMessageCollection = Await client.ListMessagesAsync()
' ...
For Each m As ImapMessage In listMessages
Console.WriteLine(String.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size))
Next m
' Disconnect.
client.Disconnect()
// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Imap class.
Imap client = new Imap();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Select 'INBOX' mailbox.
client.Select("INBOX");
// Send a command.
client.SendCommand("STAT");
// Read response from the server.
ImapResponse response = client.ReadResponse();
// Print out the response.
Console.WriteLine("Raw response: " + response.RawResponse);
foreach (ImapResponseLine line in response.GetLines())
{
Console.WriteLine("Response line: Code:{0}, Desc: {1}.", line.Code, line.Description);
}
// Close the connection.
client.Disconnect();
' IMAP server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 993
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Imap class.
Dim client As New Imap()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Select 'INBOX' mailbox.
client.Select("INBOX")
' Send a command.
client.SendCommand("STAT")
' Read response from the server.
Dim response As ImapResponse = client.ReadResponse()
' Print out the response.
Console.WriteLine("Raw response: " & response.RawResponse)
For Each line As ImapResponseLine In response.GetLines()
Console.WriteLine("Response line: Code:{0}, Desc: {1}.", line.Code, line.Description)
Next line
' Close the connection.
client.Disconnect()
Explicitly sending commands to an IMAP server is usually not necessary. High-level methods encapsulate almost all commands that could conceivably be sent to an IMAP server. However, to send a command to an IMAP server, call the SendCommand method, and to get the response from the IMAP server, call the ReadResponse method.
The example below sends the "CAPABILITY" command to an IMAP server and prints out the response:
To abort any transfer (downloading or uploading message) in progress you can either call the Cancel
method or simply close the connection by calling the Disconnect
or DisconnectAsync
method.
public void DoAbort()
{
// Create a new Imap instance.
Imap client = new Imap();
// Connect to the IMAP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("test", "test");
try
{
// Register an event handler.
client.Progress += client_Progress;
client.Select("INBOX");
// Download a message with sequence number #1.
client.DownloadMessage(1, "c:\\temp\\my message.eml");
}
catch (ImapException exc)
{
Console.WriteLine("Exception: " + exc.Message);
}
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, ImapProgressEventArgs e)
{
// Abort the download operation if the bytes transferred is greater than or equal to 500Kb.
if (e.State == ImapTransferState.Downloading && e.BytesTransferred >= 1024 * 500)
{
((Imap)sender).Cancel();
}
}
Public Sub DoAbort()
' Create a new Imap instance.
Dim client As New Imap()
' Connect to the IMAP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("test", "test")
Try
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
client.Select("INBOX")
' Download a message with sequence number #1.
client.DownloadMessage(1, "c:\temp\my message.eml")
Catch exc As ImapException
Console.WriteLine("Exception: " & exc.Message)
End Try
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As ImapProgressEventArgs)
' Abort the download operation if the bytes transferred is greater than or equal to 500Kb.
If e.State = ImapTransferState.Downloading AndAlso e.BytesTransferred >= 1024 * 500 Then
CType(sender, Imap).Cancel()
End If
End Sub
public void ShowProgress()
{
// Create a new Imap instance.
Imap client = new Imap();
// Connect to the IMAP server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("test", "test");
try
{
// Register an event handler.
client.Progress += client_Progress;
client.Select("INBOX");
// Download a message with sequence number #1.
client.DownloadMessage(1, "c:\\temp\\my message.eml");
}
catch (ImapException exc)
{
Console.WriteLine("Exception: " + exc.Message);
}
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, ImapProgressEventArgs e)
{
// Show progress information.
if (e.Length > 0 && e.State == ImapTransferState.Downloading)
{
Console.Write("\rDownloaded: {0} bytes ({1}% completed)", e.BytesTransferred, e.Percentage);
}
}
Public Sub ShowProgress()
' Create a new Imap instance.
Dim client As New Imap()
' Connect to the IMAP server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("test", "test")
Try
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
client.Select("INBOX")
' Download a message with sequence number #1.
client.DownloadMessage(1, "c:\temp\my message.eml")
Catch exc As ImapException
Console.WriteLine("Exception: " & exc.Message)
End Try
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As ImapProgressEventArgs)
' Show progress information.
If e.Length > 0 AndAlso e.State = ImapTransferState.Downloading Then
Console.Write(vbCr & "Downloaded: {0} bytes ({1}% completed)", e.BytesTransferred, e.Percentage)
End If
End Sub
When the mail message to transfer is big, and your application may take time to transfer, you may wish to show the progress of the transfer to the user. The Imap class provides progress notification through the Progress event. The Progress event is raised periodically while data transfer is in progress, making accessible necessary data to display progress information, such as the size of the file and the number of transferred bytes.
The following steps show you how to use the Progress event to display progress information while processing messages: