In previous section, I introduced how to use event handler to monitor the progress. In this section, I will introduce how to send email asynchronously in C#.
In Windows Store App, all File or .NET IO operations are based on asynchronouse mode. You should use await keyword to wait the operation is finished. With asynchronouse mode, you can do other things in your codes while the email is sending. Please have a look at the following example codes:
Note
Remarks: All of samples in this section are based on first section: Send email in A simple C# XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to use EASendMail SMTP component to send email in asynchronous mode.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// Add EASendMail and Tasks Namespace
using System.Threading.Tasks;
using EASendMail;
namespace CSharp_Windows_Store_App
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private void OnSecuring(
object sender,
SmtpStatusEventArgs e
)
{
string status = e.Status;
//status = "Securing ... ";
textStatus.Text = status;
}
private void OnAuthorized(
object sender,
SmtpStatusEventArgs e
)
{
string status = e.Status;
// status = "Authorized";
textStatus.Text = status;
}
public void OnConnected(
object sender,
SmtpStatusEventArgs e
)
{
string status = e.Status;
// status = "Connected";
textStatus.Text = status;
}
public void OnSendingDataStream(
object sender,
SmtpDataStreamEventArgs e
)
{
string status = String.Format("{0}/{1} sent", e.Sent, e.Total);
textStatus.Text = status;
}
private async void btnSend_Click(object sender, RoutedEventArgs e)
{
btnSend.IsEnabled = false;
await Send_Email();
btnSend.IsEnabled = true;
}
private async Task Send_Email()
{
String Result = "";
try
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
// Set sender email address, please change it to yours
oMail.From = new MailAddress("test@emailarchitect.net");
// Add recipient email address, please change it to yours
oMail.To.Add(new MailAddress("support@emailarchitect.net"));
// Set email subject and email body text
oMail.Subject = "test email from C# XAML project";
oMail.TextBody = "this is a test email sent from Windows Store App, do not reply";
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// If your SMTP server requires TLS connection on 25 port, please add this line
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
// If your SMTP server requires SSL connection on 465 port, please add this line
// oServer.Port = 465;
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
// Add event handlers
oSmtp.Authorized += OnAuthorized;
oSmtp.Connected += OnConnected;
oSmtp.Securing += OnSecuring;
oSmtp.SendingDataStream += OnSendingDataStream;
// get a asynchronous action object.
IAsyncAction asyncObj = oSmtp.SendMailAsync(oServer, oMail);
// do something while the email is sending.
// wait for the asynchronous operation is finished.
await asyncObj;
Result = "Email was sent successfully!";
}
catch (Exception ep)
{
Result = String.Format("Failed to send email with the following error: {0}", ep.Message);
}
// Display Result by Diaglog box
Windows.UI.Popups.MessageDialog dlg = new
Windows.UI.Popups.MessageDialog(Result);
await dlg.ShowAsync();
}
}
}
In above codes, SendMailAsync method returns a IAsyncAction object, we can also use this object to cancel current email sending. Please have a look at the following codes:
To run the following codes, you need to add another Button to the MainPage.xaml and set its name to “btnCancel”
Source codes in MainPage.xaml
<Page
x:Class="CSharp_Windows_Store_App.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CSharp_Windows_Store_App"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button Content="Button" Name="btnSend" HorizontalAlignment="Left"
Height="48" Margin="409,100,0,0" VerticalAlignment="Top" Width="182" Click="btnSend_Click"/>
<TextBlock HorizontalAlignment="Left" Name="textStatus" Height="32"
Margin="409,246,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="863"/>
<Button Content="Button" Name="btnCancel" HorizontalAlignment="Left"
Height="45" Margin="730,124,0,0" VerticalAlignment="Top" Width="160" Click="btnCancel_Click"/>
</Grid>
</Page>
Source codes in MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// Add EASendMail and Tasks Namespace
using System.Threading.Tasks;
using EASendMail;
namespace CSharp_Windows_Store_App
{
public sealed partial class MainPage : Page
{
// Declare asynchronous action object
private IAsyncAction asyncCancel = null;
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private void OnSecuring(
object sender,
SmtpStatusEventArgs e
)
{
string status = e.Status;
//status = "Securing ... ";
textStatus.Text = status;
}
private void OnAuthorized(
object sender,
SmtpStatusEventArgs e
)
{
string status = e.Status;
// status = "Authorized";
textStatus.Text = status;
}
public void OnConnected(
object sender,
SmtpStatusEventArgs e
)
{
string status = e.Status;
// status = "Connected";
textStatus.Text = status;
}
public void OnSendingDataStream(
object sender,
SmtpDataStreamEventArgs e
)
{
string status = String.Format("{0}/{1} sent", e.Sent, e.Total);
textStatus.Text = status;
}
private async void btnSend_Click(object sender, RoutedEventArgs e)
{
btnSend.IsEnabled = false;
await Send_Email();
asyncCancel = null;
btnSend.IsEnabled = true;
btnCancel.IsEnabled = false;
}
private async Task Send_Email()
{
String Result = "";
asyncCancel = null;
try
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
// Set sender email address, please change it to yours
oMail.From = new MailAddress("test@emailarchitect.net");
// Add recipient email address, please change it to yours
oMail.To.Add(new MailAddress("support@emailarchitect.net"));
// Set email subject
oMail.Subject = "test email from C# XAML project";
// Set email body
oMail.TextBody = "this is a test email sent from Windows Store App, do not reply";
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test@emailarchitect.net";
oServer.Password = "testpassword";
// If your SMTP server requires TLS connection on 25 port, please add this line
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
// If your SMTP server requires SSL connection on 465 port, please add this line
// oServer.Port = 465;
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
// Add event handlers
oSmtp.Authorized += OnAuthorized;
oSmtp.Connected += OnConnected;
oSmtp.Securing += OnSecuring;
oSmtp.SendingDataStream += OnSendingDataStream;
btnCancel.IsEnabled = true;
// get the asynchronous object
asyncCancel = oSmtp.SendMailAsync(oServer, oMail);
// do something while the email is sending.
// wait for the asynchronous operation is finished.
await asyncCancel;
Result = "Email was sent successfully!";
}
catch (Exception ep)
{
Result = String.Format("Failed to send email with the following error: {0}", ep.Message);
}
// Display Result by Diaglog box
Windows.UI.Popups.MessageDialog dlg = new
Windows.UI.Popups.MessageDialog(Result);
await dlg.ShowAsync();
}
// Cancel email sending
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
btnCancel.IsEnabled = false;
if (asyncCancel != null)
{
asyncCancel.Cancel();
}
}
}
}
Next Section
At next section I will introduce how to send email using Exchange Web Service - EWS.
Appendix
Comments
If you have any comments or questions about above example codes, please click here to add your comments.