Ultimate Mail makes it easy for you to establish secure and non-secure connections to your POP3 servers.
To connect and authenticate to a POP3 server, you can perform the following steps
Pop3
class.Connect
methods.Disconnect
method to close the POP3 session when done.// Create a new instance of the Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the POP3 port with
// client.Connect("myserver", 110);
// Login to the server.
client.Authenticate("user", "password");
StringBuilder sb = new StringBuilder();
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.Size | Pop3EnvelopeParts.UniqueId);
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].UniqueId);
}
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the POP3 port with
' client.Connect("myserver", 110);
' Login to the server.
client.Authenticate("user", "password")
Dim sb As New StringBuilder()
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.Size Or Pop3EnvelopeParts.UniqueId)
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).UniqueId)
Next i
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()
// Create a new instance of the Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect("myserver", 143, SslSecurityMode.Explicit);
// Login to the server.
client.Authenticate("user", "password");
StringBuilder sb = new StringBuilder();
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.Size | Pop3EnvelopeParts.UniqueId);
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].UniqueId);
}
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' 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 Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.Size Or Pop3EnvelopeParts.UniqueId)
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).UniqueId)
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 POP3 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 Sftp
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 Sftp
class.
The example following will show you how to do that:
public void HandleCertificateReceivedEvent()
{
// Create a new instance.
Pop3 client = new Pop3();
client.CertificateReceived += client_CertificateReceived;
// Connect to the POP3 server.
client.Connect("myserver", 110, 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 Pop3()
AddHandler client.CertificateReceived, AddressOf client_CertificateReceived
' Connect to the POP3 server.
client.Connect("myserver", 110, 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.
Pop3 client = new Pop3();
// 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 POP3 server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("userName", "password");
// Do something here...
// ...
StringBuilder sb = new StringBuilder();
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.Size | Pop3EnvelopeParts.UniqueId);
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].UniqueId);
}
Console.WriteLine(sb.ToString());
// Disconnect.
client.Disconnect();
' Create a new instance.
Dim client As New Pop3()
' 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 POP3 server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("userName", "password")
' Do something here...
' ...
Dim sb As New StringBuilder()
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.Size Or Pop3EnvelopeParts.UniqueId)
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).UniqueId)
Next i
Console.WriteLine(sb.ToString())
' Disconnect.
client.Disconnect()
The Pop3 class fully supports many proxy servers (often referred to as "proxies"). If you need to connect to your POP3 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 Pop3
class, and the necessary proxy communication will take place.
The Pop3 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 Pop3 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 Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the POP3 port with
// client.Connect("myserver", 110);
// Login to the server.
client.Authenticate("user", "password");
StringBuilder sb = new StringBuilder();
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.Size | Pop3EnvelopeParts.UniqueId);
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].UniqueId);
}
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the POP3 port with
' client.Connect("myserver", 110);
' Login to the server.
client.Authenticate("user", "password")
Dim sb As New StringBuilder()
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.Size Or Pop3EnvelopeParts.UniqueId)
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).UniqueId)
Next i
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()
// Create a new instance of the Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the POP3 port with
// client.Connect("myserver", 110);
// Login to the server using NTLM authentication method.
client.Authenticate("user", "password", Pop3AuthenticationMethod.Ntlm);
StringBuilder sb = new StringBuilder();
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.Size | Pop3EnvelopeParts.UniqueId);
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].UniqueId);
}
Console.WriteLine(sb.ToString());
// Close the connection.
client.Disconnect();
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the POP3 port with
' client.Connect("myserver", 110);
' Login to the server using NTLM authentication method.
client.Authenticate("user", "password", Pop3AuthenticationMethod.Ntlm)
Dim sb As New StringBuilder()
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.Size Or Pop3EnvelopeParts.UniqueId)
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).UniqueId)
Next i
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()
To authenticate to an POP3 server using NTLM, specify the enum value Pop3AuthenticationMethod.Ntlm
when calling the Authenticate
method.
When connecting to a secure POP3/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.
Pop3 client = new Pop3();
client.CertificateRequired += client_CertificateRequired;
// Connect to the POP3 server.
client.Connect("myserver", 110, 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 Pop3()
AddHandler client.CertificateRequired, AddressOf client_CertificateRequired
' Connect to the POP3 server.
client.Connect("myserver", 110, 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 Pop3
class to get notified when an event is triggered.
The CertificateRequired
event is triggered when a client certificate is required by the Pop3 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.
Pop3 client = new Pop3();
client.CertificateRequired += client_CertificateRequired;
// Connect to the POP3 server.
client.Connect("myserver", 110, 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 Pop3()
AddHandler client.CertificateRequired, AddressOf client_CertificateRequired
' Connect to the POP3 server.
client.Connect("myserver", 110, 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.
Pop3 client = new Pop3();
client.CertificateReceived += client_CertificateReceived;
// Connect to the POP3 server.
client.Connect("myserver", 110, 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 Pop3()
AddHandler client.CertificateReceived, AddressOf client_CertificateReceived
' Connect to the POP3 server.
client.Connect("myserver", 110, 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 Pop3 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.
private long _messageSize;
public void ShowProgress()
{
// Create a new Pop3 instance.
Pop3 client = new Pop3();
// Connect to the POP3 server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("test", "test");
try
{
// Register an event handler.
client.Progress += client_Progress;
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.Size | Pop3EnvelopeParts.MessageInboxIndex);
// Download the first message.
_messageSize = list[0].Size;
// Download the first one.
client.DownloadMessage(list[0].MessageInboxIndex, "c:\\temp\\my message.eml");
}
catch (Pop3Exception exc)
{
Console.WriteLine("Exception: " + exc.Message);
}
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, Pop3ProgressEventArgs e)
{
// Show progress information.
if (e.State == Pop3TransferState.Downloading)
{
Console.Write("\rDownloaded: {0} bytes ({1}% completed)", e.BytesTransferred, e.CalculatePercentage(_messageSize));
}
}
Private _messageSize As Long
Public Sub ShowProgress()
' Create a new Pop3 instance.
Dim client As New Pop3()
' Connect to the POP3 server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("test", "test")
Try
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.Size Or Pop3EnvelopeParts.MessageInboxIndex)
' Download the first message.
_messageSize = list(0).Size
' Download the first one.
client.DownloadMessage(list(0).MessageInboxIndex, "c:\temp\my message.eml")
Catch exc As Pop3Exception
Console.WriteLine("Exception: " & exc.Message)
End Try
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As Pop3ProgressEventArgs)
' Show progress information.
If e.State = Pop3TransferState.Downloading Then
Console.Write(vbCr & "Downloaded: {0} bytes ({1}% completed)", e.BytesTransferred, e.CalculatePercentage(_messageSize))
End If
End Sub
public void HandleCommandSentResponseReadEvents()
{
// Create a new instance.
Pop3 client = new Pop3();
// Register event handlers.
client.CommandResponse += client_CommandResponse;
// Connect to the POP3 server.
client.Connect("server");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Do something here
// ...
StringBuilder sb = new StringBuilder();
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.Size | Pop3EnvelopeParts.UniqueId);
for (int i = 0; i < list.Count; i++)
{
sb.AppendFormat("{0} - {1}\r\n", i + 1, list[i].UniqueId);
}
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 Pop3()
' Register event handlers.
AddHandler client.CommandResponse, AddressOf client_CommandResponse
' Connect to the POP3 server.
client.Connect("server")
' Authenticate.
client.Authenticate("test", "test")
' ...
' Do something here
' ...
Dim sb As New StringBuilder()
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.Size Or Pop3EnvelopeParts.UniqueId)
For i As Integer = 0 To list.Count - 1
sb.AppendFormat("{0} - {1}" & vbCrLf, i + 1, list(i).UniqueId)
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 POP3 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 Pop3
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.
Pop3 client = new Pop3();
client.StateChanged += client_StateChanged;
// Connect to the POP3 server.
client.Connect("server");
// Authenticate.
client.Authenticate("test", "test");
// ...
// Do something here
// ...
// Disconnect.
client.Disconnect();
}
void client_StateChanged(object sender, Pop3StateChangedEventArgs e)
{
Console.WriteLine("State changed, old state: {0}, new state: {1}", e.OldState, e.OldState);
}
Public Sub HandleStateChangedEvent()
' Create a new instance.
Dim client As New Pop3()
AddHandler client.StateChanged, AddressOf client_StateChanged
' Connect to the POP3 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 Pop3StateChangedEventArgs)
Console.WriteLine("State changed, old state: {0}, new state: {1}", e.OldState, e.OldState)
End Sub
The Pop3
class also has a comprehensive API to manage mail messages.
// POP3 server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 995;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Get the message list.
Console.WriteLine("Getting message list...");
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.MessageInboxIndex | Pop3EnvelopeParts.Size);
// Get messages.
for (int i = 0; i < list.Count; i++)
{
Pop3Message pop3Message = list[i];
// Download the message to an instance of the MailMessage class.
MailMessage msg = client.DownloadMailMessage(pop3Message.MessageInboxIndex);
// Display some information about it.
Console.WriteLine("Size: " + pop3Message.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();
' POP3 server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 995
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Get the message list.
Console.WriteLine("Getting message list...")
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.MessageInboxIndex Or Pop3EnvelopeParts.Size)
' Get messages.
For i As Integer = 0 To list.Count - 1
Dim pop3Message As Pop3Message = list(i)
' Download the message to an instance of the MailMessage class.
Dim msg As MailMessage = client.DownloadMailMessage(pop3Message.MessageInboxIndex)
' Display some information about it.
Console.WriteLine("Size: " & pop3Message.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 a POP3 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 a POP3 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()
{
// POP3 server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 995;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Get the message list.
Console.WriteLine("Getting message list...");
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.UniqueId | Pop3EnvelopeParts.MessageInboxIndex);
// Get messages.
for (int i = 0; i < list.Count; i++)
{
Pop3Message 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.MessageInboxIndex);
client.DownloadMessage(message.MessageInboxIndex, 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()
' POP3 server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 995
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Get the message list.
Console.WriteLine("Getting message list...")
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.UniqueId Or Pop3EnvelopeParts.MessageInboxIndex)
' Get messages.
For i As Integer = 0 To list.Count - 1
Dim message As Pop3Message = 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.MessageInboxIndex)
client.DownloadMessage(message.MessageInboxIndex, 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
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "password";
const int port = 995;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
Pop3 client = new Pop3();
try
{
Console.WriteLine("Connecting POP3 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);
// Get mailbox info.
Pop3MailboxStat info = client.GetMailboxStat();
// Show the number of messages in the selected folder.
Console.WriteLine("{0} messages found.", info.MessageCount);
// Get the message list.
Console.WriteLine("Getting message list...");
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.FullHeaders);
Pop3Message 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(Pop3EnvelopeParts.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("Inbox Index: {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 (Pop3Exception pop3Exc)
{
Console.WriteLine(string.Format("An POP3 error occurred: {0}, ErrorStatus: {1}", pop3Exc.Message, pop3Exc.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 = 995
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
Dim client As New Pop3()
Try
Console.WriteLine("Connecting POP3 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)
' Get mailbox info.
Dim info As Pop3MailboxStat = client.GetMailboxStat()
' Show the number of messages in the selected folder.
Console.WriteLine("{0} messages found.", info.MessageCount)
' Get the message list.
Console.WriteLine("Getting message list...")
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.FullHeaders)
Dim message As Pop3Message
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(Pop3EnvelopeParts.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("Inbox Index: {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 pop3Exc As Pop3Exception
Console.WriteLine(String.Format("An POP3 error occurred: {0}, ErrorStatus: {1}", pop3Exc.Message, pop3Exc.Status))
Catch exc As Exception
Console.WriteLine(String.Format("An error occurred: {0}", exc.Message))
End Try
You can retrieve all message headers by simply calling the ListMessages with parameter Pop3EnvelopeParts.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:
The Pop3
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 the 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:
The Pop3
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.
The library also comes with some advanced features below:
Pop3
provides several methods allowing you to asynchronously connect, log in, upload, download, etc. Their names always end with Async. This means the method will begin 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 a POP3 server and list messages asynchronously:
// Create a new instance of the Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the POP3 port with
// client.Connect("myserver", 110);
// Login to the server.
client.Authenticate("user", "password");
// ...
// List all messages in the selected folder.
Pop3MessageCollection listMessages = await client.ListMessagesAsync(Pop3EnvelopeParts.UniqueId | Pop3EnvelopeParts.Size);
// ...
foreach (Pop3Message m in listMessages)
{
Console.WriteLine(string.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size));
}
// Disconnect.
client.Disconnect();
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the POP3 port with
' client.Connect("myserver", 110);
' Login to the server.
client.Authenticate("user", "password")
' ...
' List all messages in the selected folder.
Dim listMessages As Pop3MessageCollection = Await client.ListMessagesAsync(Pop3EnvelopeParts.UniqueId Or Pop3EnvelopeParts.Size)
' ...
For Each m As Pop3Message In listMessages
Console.WriteLine(String.Format("UniqueId: {0}, Size: {1}", m.UniqueId, m.Size))
Next m
' Disconnect.
client.Disconnect()
// POP3 server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 995;
const SslSecurityMode securityMode = SslSecurityMode.Implicit;
// Create a new instance of the Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Send a command.
client.SendCommand("HELP", false);
// Read response from the server.
string response = client.ReadResponse();
// Print out the response.
Console.WriteLine(response);
// Close the connection.
client.Disconnect();
' POP3 server information.
Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 995
Const securityMode As SslSecurityMode = SslSecurityMode.Implicit
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Send a command.
client.SendCommand("HELP", False)
' Read response from the server.
Dim response As String = client.ReadResponse()
' Print out the response.
Console.WriteLine(response)
' Close the connection.
client.Disconnect()
Explicitly sending commands to a POP3 server is usually not necessary. High-level methods encapsulate almost all commands that could conceivably be sent to a POP3 server. However, to send a command to a POP3 server, call the SendCommand method, and to get the response from the POP3 server, call the ReadResponse method.
The example below sends the "CAPABILITY" command to a POP3 server and prints out the response:
The simplest way to obtain information about a specified mailbox is using GetMailboxStat
method. The method returns a Pop3MailboxStat
object containing information about the mailbox you have requested.
// Create a new instance of the Pop3 class.
Pop3 client = new Pop3();
// Connect to the server.
client.Connect("myserver");
// Or you can specify the POP3 port with
// client.Connect("myserver", 110);
// Login to the server.
client.Authenticate("user", "password");
// Obtain mailbox information.
Pop3MailboxStat info = client.GetMailboxStat();
// Print out some information.
Console.WriteLine("Number of messages found: {0}", info.MessageCount);
Console.WriteLine("Mailbox Size: {0}", info.Size);
// Close the connection.
client.Disconnect();
' Create a new instance of the Pop3 class.
Dim client As New Pop3()
' Connect to the server.
client.Connect("myserver")
' Or you can specify the POP3 port with
' client.Connect("myserver", 110);
' Login to the server.
client.Authenticate("user", "password")
' Obtain mailbox information.
Dim info As Pop3MailboxStat = client.GetMailboxStat()
' Print out some information.
Console.WriteLine("Number of messages found: {0}", info.MessageCount)
Console.WriteLine("Mailbox Size: {0}", info.Size)
' Close the connection.
client.Disconnect()
public void DoAbort()
{
// Create a new Pop3 instance.
Pop3 client = new Pop3();
// Connect to the POP3 server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("test", "test");
try
{
// Register an event handler.
client.Progress += client_Progress;
// Download a message with sequence number #1.
client.DownloadMessage(1, "c:\\temp\\my message.eml");
}
catch (Pop3Exception exc)
{
Console.WriteLine("Exception: " + exc.Message);
}
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, Pop3ProgressEventArgs e)
{
// Abort the download operation if the bytes transferred is greater than or equal to 500Kb.
if (e.State == Pop3TransferState.Downloading && e.BytesTransferred >= 1024 * 500)
{
((Pop3)sender).Cancel();
}
}
Public Sub DoAbort()
' Create a new Pop3 instance.
Dim client As New Pop3()
' Connect to the POP3 server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("test", "test")
Try
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
' Download a message with sequence number #1.
client.DownloadMessage(1, "c:\temp\my message.eml")
Catch exc As Pop3Exception
Console.WriteLine("Exception: " & exc.Message)
End Try
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As Pop3ProgressEventArgs)
' Abort the download operation if the bytes transferred is greater than or equal to 500Kb.
If e.State = Pop3TransferState.Downloading AndAlso e.BytesTransferred >= 1024 * 500 Then
CType(sender, Pop3).Cancel()
End If
End Sub
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.
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 Pop3 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 transferring a file:
private long _messageSize;
public void ShowProgress()
{
// Create a new Pop3 instance.
Pop3 client = new Pop3();
// Connect to the POP3 server.
client.Connect("myserver");
// Authenticate.
client.Authenticate("test", "test");
try
{
// Register an event handler.
client.Progress += client_Progress;
Pop3MessageCollection list = client.ListMessages(Pop3EnvelopeParts.Size | Pop3EnvelopeParts.MessageInboxIndex);
// Download the first message.
_messageSize = list[0].Size;
// Download the first one.
client.DownloadMessage(list[0].MessageInboxIndex, "c:\\temp\\my message.eml");
}
catch (Pop3Exception exc)
{
Console.WriteLine("Exception: " + exc.Message);
}
// Disconnect.
client.Disconnect();
}
void client_Progress(object sender, Pop3ProgressEventArgs e)
{
// Show progress information.
if (e.State == Pop3TransferState.Downloading)
{
Console.Write("\rDownloaded: {0} bytes ({1}% completed)", e.BytesTransferred, e.CalculatePercentage(_messageSize));
}
}
Private _messageSize As Long
Public Sub ShowProgress()
' Create a new Pop3 instance.
Dim client As New Pop3()
' Connect to the POP3 server.
client.Connect("myserver")
' Authenticate.
client.Authenticate("test", "test")
Try
' Register an event handler.
AddHandler client.Progress, AddressOf client_Progress
Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.Size Or Pop3EnvelopeParts.MessageInboxIndex)
' Download the first message.
_messageSize = list(0).Size
' Download the first one.
client.DownloadMessage(list(0).MessageInboxIndex, "c:\temp\my message.eml")
Catch exc As Pop3Exception
Console.WriteLine("Exception: " & exc.Message)
End Try
' Disconnect.
client.Disconnect()
End Sub
Private Sub client_Progress(ByVal sender As Object, ByVal e As Pop3ProgressEventArgs)
' Show progress information.
If e.State = Pop3TransferState.Downloading Then
Console.Write(vbCr & "Downloaded: {0} bytes ({1}% completed)", e.BytesTransferred, e.CalculatePercentage(_messageSize))
End If
End Sub