Sending emails from your Android, iOS, or Windows Mobile Devices with Ultimate Mail for Mobile

You can easily send emails from your mobile devices with just a few lines of C# code. From version 6.0 Ultimate Mail also includes support for Android and iOS platforms in addition to Windows, Linux and MAC OS X with .NET Framework and Mono.

With Ultimate Mail you can load your messages in EML or Outlook format using the same Load method. This is the screenshot of an example to load message from templates and send emails on iOS:

Mail-Template-iOS

This is the screenshot of an example to send emails on Android:

SMTP Config

The following code snippet is taken from an example for iOS to send emails:

Smtp client = null;
try
{
client = new Smtp ();
await client.ConnectAsync(ServerName, ServerPort, Mode);
}
catch (Exception ex)
{
_window.Busy = false;
Util.ShowException(ex);
return;
}

if (!string.IsNullOrEmpty(UserName))
{
try
{
await client.AuthenticateAsync(UserName, Password);
}
catch (Exception ex)
{
_window.Busy = false;
Util.ShowException(ex);
return;
}
}

try
{
await client.SendAsync(_message);
}
catch (Exception ex)
{
_window.Busy = false;
Util.ShowException(ex);
return;
}

IMAP, POP3 and SMTP Settings for Yahoo! Mail

Yahoo! IMAP, POP3 and SMTP connections dont require SSL enabled. The following table shows the available settings to establish connections to Yahoo! Mail servers:

Protocol Port Security Mode Server
IMAP 143
993
143
Unsecure
Implicit
Explicit
imap.mail.yahoo.com
POP3 110
995
110
Unsecure
Implicit
Explicit
pop.mail.yahoo.com
SMTP 587
465
Unsecure
Implicit
smtp.mail.yahoo.com

The following example code show you how to connect Yahoo! Mail Servers:

// Create a new instance of the ImapClient class and download a message.
using (ImapClient client = new ImapClient())
{
// Connect to the server.
client.Connect("imap.mail.yahoo.com", 993, SecurityMode.Implicit);
// Login to the server.
client.Authenticate("mytest@yahoo.com", "password");

// Download a message to an instance of the MailMessage class.
MailMessage msg = client.DownloadMailMessage(imapMessageUniqueId);
}

// Create a new instance of the Pop3Client class and download a message.
using (Pop3Client client = new Pop3Client())
{
// Connect to the server.
client.Connect("pop.mail.yahoo.com", 995, SecurityMode.Implicit);
// Login to the server.
client.Authenticate("mytest@yahoo.com", "password");

// Download the message to an instance of the MailMessage class.
MailMessage msg = client.DownloadMailMessage(pop3MessageSequenceNumber);
}

// Create a new instance of the SmtpClient class and send an email.
using (SmtpClient client = new SmtpClient())
{
// Connect to the server.
client.Connect("smtp.mail.yahoo.com", 587);
// Login to the server.
client.Authenticate("mytest@yahoo.com", "password");

// Create a new mail message.
MailMessage msg = new MailMessage();
msg.Subject = "Test Subject";
msg.BodyText = "Content";
msg.From = "from@mydomain.com";
msg.To = "to@somedomain.com";
// And send it.
client.Send(msg);
}

Sending mail with attachments

MIME attachments are represented by Attachment objects, and are managed by use of the MailMessage.Attachments property. The source of attachments can be a file, a MemoryStream, or any other type of .NET Framework Stream. As a result, the ways an attachment can be created is limitless. This topic demonstrates two ways of creating an attachment.

C#:

const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 465;
const SecurityMode securityMode = SecurityMode.Implicit;
SmtpClient client = new SmtpClient();
try
{
   MailMessage mmMessage = new MailMessage();
   mmMessage.From.Add("from@thedomain.com");
   mmMessage.To.Add("name@domain.com");
   mmMessage.Subject = "Test Subject";
   mmMessage.BodyText = "Test Content";
   // Attach file to the message.
   mmMessage.Attachments.Add("myfile.dat");
   // Attach content data from a stream to the message.
   Stream stream = new FileStream("myfile.dat", FileMode.Open);
   // The stream will be automatically closed after adding to the attachment list.
   mmMessage.Attachments.Add(new Attachment(stream, "teststream"));
   Console.WriteLine("Connecting SMTP 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);
   Console.WriteLine("Sending the message with attachment...");
   client.Send(mmMessage);
   Console.WriteLine("Message sent...");
   // Disconnect.
   Console.WriteLine("Disconnecting...");
   client.Disconnect();
}
catch (SmtpException smtpExc)
{
   MessageBox.Show(string.Format("An SMTP error occurred: {0}, ErrorStatus: {1}", smtpExc.Message, smtpExc.Status));
}
catch (Exception exc)
{
   MessageBox.Show(string.Format("An error occurred: {0}", exc.Message));
}

VB.NET:

Const serverName As String = "myserver"
Const user As String = "name@domain.com"
Const password As String = "mytestpassword"
Const port As Integer = 465
Const securityMode As SecurityMode = securityMode.Implicit
Dim client As New SmtpClient()
Try
    Dim mmMessage As New MailMessage()
    mmMessage.From.Add("from@thedomain.com")
    mmMessage.To.Add("name@domain.com")
    mmMessage.Subject = "Test Subject"
    mmMessage.BodyText = "Test Content"
    ' Attach file to the message.
    mmMessage.Attachments.Add("myfile.dat")
    ' Attach content data from a stream to the message.
    Dim stream As Stream = New FileStream("myfile.dat", FileMode.Open)
    ' The stream will be automatically closed after adding to the attachment list.
    mmMessage.Attachments.Add(New Attachment(stream, "teststream"))
    Console.WriteLine("Connecting SMTP 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)
    Console.WriteLine("Sending the message with attachment...")
    client.Send(mmMessage)
    Console.WriteLine("Message sent...")
    ' Disconnect.
    Console.WriteLine("Disconnecting...")
    client.Disconnect()
Catch smtpExc As SmtpException
    MessageBox.Show(String.Format("An SMTP error occurred: {0}, ErrorStatus: {1}", smtpExc.Message, smtpExc.Status))
Catch exc As Exception
    MessageBox.Show(String.Format("An error occurred: {0}", exc.Message))
End Try

Deleting a POP3 message

Pop3Client class provides two methods Delete for deleting messages and Undelete for undeleting messages.

You use the Delete method to mark a message as deleted. It won’t appear in subsequent message lists, but will actually only be removed from the mailbox after the session is disconnected using Disconnect method. You can recover messages that were marked as deleted by using the Undelete method.

The following steps will help you to delete a single message using the Delete method:

C#:

// POP3 server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 995;
const SecurityMode securityMode = SecurityMode.Implicit;
// Create a new instance of the Pop3Client class.
Pop3Client client = new Pop3Client();
// Connect to the server.
client.Connect(serverName, port, securityMode);
// Login to the server.
client.Authenticate(user, password);
// Delete a mail message with sequence number 1.
client.Delete(1);
// Close the connection.
client.Disconnect();

VB.NET:

' 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 SecurityMode = securityMode.Implicit
' Create a new instance of the Pop3Client class.
Dim client As New Pop3Client()
' Connect to the server.
client.Connect(serverName, port, securityMode)
' Login to the server.
client.Authenticate(user, password)
' Delete a mail message with sequence number 1.
client.Delete(1)
' Close the connection.
client.Disconnect()

Providing client’s certificate required by server

This topic explains how to authenticate the client using a certificate. IMAP servers might be configured to request the client to authenticate using its certificate during SSL negotiation. The client can either process, or inform the server that it has no suitable certificate.

The example below demonstrates how to use ComponentPro IMAP library and handle the CertificateRequired event of the ImapClient to find a suitable certificate for the client authentication:

C#:

public void HandleCertificateRequiredEvent()
{
   // Create a new instance.
   ImapClient client = new ImapClient();
   client.CertificateRequired += client_CertificateRequired;
   // Connect to the IMAP server.
   client.Connect("myserver", 143, SecurityMode.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.Certificate = 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.Certificate = certs[certIndex];
           return;
       }
       if (certIndex == 0)
           break;
       Console.WriteLine(string.Format("ERROR: You must enter number between 0 and {0}.", certs.Count));
   }
}

VB.NET

Public Sub HandleCertificateRequiredEvent()
    ' Create a new instance.
    Dim client As New ImapClient()
    AddHandler client.CertificateRequired, AddressOf client_CertificateRequired
    ' Connect to the IMAP server.
    client.Connect("myserver", 143, SecurityMode.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.Certificate = 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.Certificate = 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

Creating a new mail message

Introduction to the Non-MIME and MIME messages

Email messages can generally be separated into two broad categories:

  • Non-MIME messages.
  • MIME messages.

Non-MIME messages

A non-MIME message refers to any message that is created in the original format defined in RFC822. These messages are generally made up of simple text and Uuencoded or Yencoded attachments.

MIME messages

MIME (Multipurpose Internet Mail Extensions) was defined to expand upon the original RFC822 message structure’s ability to transport files and the inability to create a complex-multipart message. These types of messages are usually recognizable by the “MIME-VERSION : 1.0″ header line and the MIME-boundary separating the parts of the message.

Since almost all email readers today are MIME compatible, it is recommended to create all messages as MIME messages. Create a non-MIME messages only if it is likely that the mail reader used to receive the message will be unable to read MIME.

The examples below show how to create a simple mail message using the UltimateMail component:

C#:

// Create a new instance of the MailMessage class.
MailMessage msg = new MailMessage();
msg.From.Add("john@somedomain.com");
msg.To.Add("someone@somedomain.com");
msg.Subject = "Hello";
msg.BodyText = "How are you?";

VB.NET:

' Create a new instance of the MailMessage class.
Dim msg As New MailMessage()
msg.From.Add("john@somedomain.com")
msg.To.Add("someone@somedomain.com")
msg.Subject = "Hello"
msg.BodyText = "How are you?"

POP3 Server with Explicit security mode

Explicit connection and Implicit connection are two secure methods to connect to a secure SMTP/POP3/POP3 server. This topic will go in detail the Explicit connection.

Explicit connection

When the client connects to the server using SSL, an SSL negotiation is initialized, the connection is secured and all following comminuation is being protected.

The code snippet below shows how to connect to an POP3 server securely using Explicit security mode.

C#:

// Create a new instance of the Pop3Client class.
Pop3Client client = new Pop3Client();
// Connect to the server.
client.Connect("myserver", 143, SecurityMode.Explicit);
// Login to the server.
client.Authenticate("user", "password");
StringBuilder sb = new StringBuilder();
Pop3MessageCollection list = client.ListMessages(EnvelopeParts.Size | EnvelopeParts.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();

VB.NET:

' Create a new instance of the Pop3Client class.
Dim client As New Pop3Client()
' Connect to the server.
client.Connect("myserver", 143, SecurityMode.Explicit)
' Login to the server.
client.Authenticate("user", "password")
Dim sb As New StringBuilder()
Dim list As Pop3MessageCollection = client.ListMessages(EnvelopeParts.Size Or EnvelopeParts.UniqueId)
For i As Integer = 0 To list.Count - 1
    sb.AppendFormat("{0} - {1}" & Constants.vbCrLf, i + 1, list(i).UniqueId)
Next i
Console.WriteLine(sb.ToString())
' Close the connection.
client.Disconnect()

Sending a custom command to an IMAP server

Explicitly sending commands to an IMAP server is usually not necessary. Almost all commands that could conceivably be sent to an IMAP server are encapsulated by high-level methods. However, to send a command to an IMAP server, simply call the SendCommand method, and to get the response from the IMAP server, call the ReadResponse method.

The example below sends the “STAT” command to an IMAP server and print out the response:

C#:

// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SecurityMode securityMode = SecurityMode.Implicit;
// Create a new instance of the ImapClient class.
ImapClient client = new ImapClient();
// 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(response.RawResponse);
// Close the connection.
client.Disconnect();

VB.NET:

' 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 SecurityMode = securityMode.Implicit
' Create a new instance of the ImapClient class.
Dim client As New ImapClient()
' 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(response.RawResponse)
' Close the connection.
client.Disconnect()

Downloading Unread IMAP Mail Messages

To list and download unread mail messages with the Ultimate IMAP Mail component, you just need to pass the ImapCriterion.DontHaveFlags(ImapMessageFlags.Seen) search condition to the ListMessages method. The following code illustrates how to do so:

C#:

// IMAP server information.
const string serverName = "myserver";
const string user = "name@domain.com";
const string password = "mytestpassword";
const int port = 993;
const SecurityMode securityMode = SecurityMode.Implicit;
// Create a new instance of the ImapClient class.
ImapClient client = new ImapClient();
// 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(EnvelopeParts.UniqueId | EnvelopeParts.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();

VB.NET:

' 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 SecurityMode = securityMode.Implicit
' Create a new instance of the ImapClient class.
Dim client As New ImapClient()
' 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(EnvelopeParts.UniqueId Or EnvelopeParts.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()

Sending Mail to Multiple Recipients

This topic illustrates how to compose an email message and send it to multiple recipients with a single line of code. ComponentPro UltimateMail makes sending to multiple recipients easy to manage, by representing these types as collections of the MailMessage object.

If you are using the component to send emails through Gmail SMTP, you need to set the server name to smtp.gmail.com, port to 465, and security mode to Implicit. The following image shows you the configuration in the SMTP Send Mail sample project:

Ultimate SMTP Send Mail

Using Ultimate Mail Library to send mails:

First, you need to connect to the server with a specified port and security mode, authenticate the user if required and call the Send method to send the message to the recipients. Before using the SmtpClient class, you need to add using directive for the namespace ComponentSoft.Net. The following example takes advantage of the easy-to-use features of the library.

C#

const string serverName = “myserver”;
const string user = name@domain.com;
const string password = “mytestpassword”;
const int port = 465;
const SecurityMode securityMode = SecurityMode.Implicit;
SmtpClient client =
 new SmtpClient();
try
{
MailMessage mmMessage = new MailMessage();
mmMessage.From.Add(
from@thedomain.com);
mmMessage.To.Add(
name@domain.com);
mmMessage.To.Add(
someone@domain.com);
mmMessage.Cc.Add(
someone2@domain.com);
mmMessage.Bcc.Add(
someone3@domain.com);
mmMessage.Subject =
 “Test Subject”;
mmMessage.BodyText =
 “Test Content”;
Console.WriteLine(
“Connecting SMTP server: {0}:{1}…”, serverName, port);
// Connect to the server. (i.e. componentsoft.net)
client.Connect(serverName, port, securityMode);
// Login to the server.
Console.WriteLine(“Logging in as {0}…”, user);
client.Authenticate(user, password);
Console.WriteLine(
“Sending mail message…”);
client.Send(mmMessage);
Console.WriteLine(
“Message sent…”);
// Disconnect.
Console.WriteLine(“Disconnecting…”);
client.Disconnect();
}
catch (SmtpException smtpExc)
{
MessageBox.Show(
string.Format(“An SMTP error occurred: {0}, ErrorStatus: {1}”, smtpExc.Message, smtpExc.Status));
}
catch (Exception exc)
{
MessageBox.Show(
string.Format(“An error occurred: {0}”, exc.Message));
}

VB.NET

Const serverName As String = “myserver”
Const user As String = “name@domain.com”
Const password As String = “mytestpassword”
Const port As Integer = 465
Const securityMode As SecurityMode = securityMode.Implicit
Dim client As New SmtpClient()
Try
Dim mmMessage As New MailMessage()
mmMessage.From.Add(“from@thedomain.com”)
mmMessage.To.Add(“name@domain.com”)
mmMessage.To.Add(“someone@domain.com”)
mmMessage.Cc.Add(“someone2@domain.com”)
mmMessage.Bcc.Add(“someone3@domain.com”)
mmMessage.Subject = “Test Subject”
mmMessage.BodyText = “Test Content”
Console.WriteLine(“Connecting SMTP 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)
Console.WriteLine(“Sending mail message…”)
client.Send(mmMessage)
Console.WriteLine(“Message sent…”)
‘ Disconnect.
Console.WriteLine(“Disconnecting…”)
client.Disconnect()
Catch smtpExc As SmtpException
MessageBox.Show(String.Format(“An SMTP error occurred: {0}, ErrorStatus: {1}”, smtpExc.Message, smtpExc.Status))
Catch exc As Exception
MessageBox.Show(String.Format(“An error occurred: {0}”, exc.Message))
End Try