Send Email in C# from Windows Store Apps - XAML - UWP - Tutorial

EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). It also supports Exchange Server Web Service and WebDAV protocols. This tutorial introduces how to send email in C# XAML Windows Store App using SMTP. It also demonstrates SSL, Embedded Images, Asynchronous Mode and Multiple Threads usage.

This tutorial is for C# XAML Windows Store Apps/UWP. If you want to send email in .NET framework application, please go to Send Email in C# from .NET framework - Tutorial

Send email in a simple C# XAML Windows Store App project

To better demonstrate how to send email using SMTP protocol, let’s create a C# XAML Windows Store App project at first, and then add the reference of EASendMail in your project.

c# windows store app project

After you created the project, double click “MainPage.xaml” and use “Toolbox” to put a Button and a TextBlock control on the XAML page. Set Button control name to “btnSend” and set TextBlock control name to “textStatus”.

c# windows store app project

The source code in MainPage.xaml is like this:

<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"/>
        <TextBlock HorizontalAlignment="Left" Name="textStatus" Height="32"
     Margin="409,246,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="863"/>
    </Grid>
</Page>

Installation

EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). It also supports Exchange Web Service (EWS) and WebDAV protocols. Before you can use the following example codes, you should download the EASendMail Installer and install it on your machine at first.

Install from NuGet

You can also install the run-time assembly by NuGet. Run the following command in the NuGet Package Manager Console:

Install-Package EASendMail

Note

If you install it by NuGet, no sample projects are installed, only .NET assembly is installed.

Add Reference

To use EASendMail SMTP Component in your Windows Store App/UWP project, the first step is “Add reference of EASendMail to your project”. Please create/open your project with Visual Studio, then select menu -> Project -> Add Reference -> Browse -> Browse..., and select the Installation Path\Lib\[portable/uap]\EASendMail.winmd from local disk, click Open -> OK, the reference will be added to your project, and you can start to use EASendMail SMTP Component in your project.

SMTP Component for Windows Store App

Windows Runtime Assembly

After compiling your project, a copy of EASendMail.winmd will be generated by compiler in same folder of your application executable file. Packing all the *.winmd, *.dll and *.exe in the folder to installer is ok. As EASendMail.winmd is a pure Windows 8/10 Runtime Component, it doesn’t require “Regsvr32” (self-register) to register the dll.

File .NET Framework Version
Lib\portable-win81+wpa81\EASendMail.winmd Built with .NET Framework 4.5.1
It requires Windows Store App Runtime 8.1 or later version.
Lib\uap10.0\EASendMail.winmd Built with Universal Windows Platform.
It requires Windows 10 or later version (Universal Windows Platform).

Now, please double-click the Button on the XAML page, VS 2012 will generate the codes for OnClick event automatically. The source codes in MainPage.xaml.cs is like this:

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;

namespace CSharp_Windows_Store_App
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}

[C# - Send email from Windows Store App - XAML]

Now add the following codes to the project and change From, To, Server, User and Password to corresponding value and compile your project.

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 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 SMTP 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;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

If you set everything right, click the button, you can get “email was sent successfully”. If you get “failed to send email with the following error:”, then please have a look at the following section.

Common SMTP Transport Error

When you execute above example code, if it threw an exception about “Networking connection” or “No such host”, it is likely that your SMTP server address is not correct. If it threw an exception about “5xx Relay denied”, it is likely that you did not set user authentication. Another common error is “5xx Must issue a STARTTLS command first” or “No supported authentication marshal found!”, that is because your SMTP server requires user authentication under SSL connection. You can set the SSL connection to solve this problem. You can learn more detail in Troubleshooting section.

Where can I get my SMTP email server address, user and password?

Because each email account provider has different server address, so you should query your SMTP server address from your email account provider. To prevent spreading email from the server, most SMTP servers also require user authentication. User name is your email address or your email address without domain part, it depends on your email provider setting.

When you execute above example code, if you get error about “Networking connection” or “No such host”, it is likely that your SMTP server address is not correct. If you get an error like “5xx Relay denied”, it is likely that you did not set user authentication. Another common error is “5xx Must issue a STARTTLS command first” or “No supported authentication marshal found!”, that is because your SMTP server requires user authentication under SSL connection. You can set the SSL connection to solve this problem.

Finally, if you have already set your account in your email client such as Outlook or Window Mail, you can query your SMTP server address, user in your email client. For example, you can choose menu -> “Tools” - > - “Accounts” - > “Your email account” - > “Properties” - > “Servers” in Outlook express or Windows Mail to get your SMTP server, user. Using EASendMail to send email does not require you have email client installed on your machine or MAPI, however you can query your exist email accounts in your email client.

c# xaml email sample

Email Address Syntax and Multiple Recipients

The following example codes demonstrates how to specify display name and email address by different syntax.

// For single email address (From, ReplyTo, ReturnPath), the syntax can be:
// ["][display name]["]<email address>

// For example:
"Tester, T" <test@adminsystem.com>
Tester <test@adminsystem.com>
<test@adminsystem.com>
test@adminsystem.com

// For mulitple email address (To, CC, Bcc), the syntax can be:
// [single email],[single email]...
// (,;\r\n) can be used to separate multiple email addresses.

// For example:
"Tester, T" <test1@adminsystem.com>, Tester2 <test2@adminsystem.com>,
    <test3@adminsystem.com>, test4@adminsystem.com

[C# - Email Address Syntax - Example]

To better understand the email address syntax, please refer to the following codes. It demonstrate how to specify from, to, cc by different email address syntax.

// From is a MailAddress object, it supports implicit converting from string.
// The syntax is like this: "test@adminsystem.com" or "Tester<test@adminsystem.com>"
// The example code without implicit converting:
oMail.From = new MailAddress( "Tester", "test@adminsystem.com" );
oMail.From = new MailAddress( "Tester<test@adminsystem.com>");
oMail.From = new MailAddress( "test@adminsystem.com" );

// To, Cc and Bcc is a AddressCollection object, it supports implicit converting
// from string. Multiple addresses are separated with (,;)
// The syntax is like this: "test@adminsystem.com, test1@adminsystem.com"
// The example code without implicit converting:
oMail.To = new AddressCollection( "test1@adminsystem.com, test2@adminsystem.com" );
oMail.To = new AddressCollection( "Test1<test@adminsystem.com>, Test2<test2@adminsystem.com>");
// You can add more recipient by Add method:
oMail.To.Add( new MailAddress( "tester", "test@adminsystem.com"));

// You can also add carbon copy (CC) or blind carbon copy (BCC) in the email:
oMail.Cc.Add( new MailAddress( "CC recipient", "cc@adminsystem.com"));
oMail.Bcc.Add( new MailAddress( "Bcc recipient", "bcc@adminsystem.com"));

From, ReplyTo, Sender and Return-Path

From, Reply-To, Sender and Return-Path are common email headers in email message. You should always set From property at first, it is a MUST to identify the email sender. The following table lists the header and corresponding properties:

Header Property
From SmtpMail.From
Reply-To SmtpMail.ReplyTo
Sender SmtpMail.Sender
Return-Path SmtpMail.ReturnPath
  • From

    This property indicates the original email sender. This is what you see as the “FROM” in most mail clients.

  • Reply-To

    This property indicates the reply address. Basically, when the user clicks “reply” in mail client, the Reply-To value should be used as the recpient address of the replied email. If you don’t set this property, the Reply address is same as From address.

  • Sender

    This property indicates the who submit/send the email. When the user received the email, the email client displays: From: “sender address” on behalf of “from address”. If you don’t set this property, the Sender address is same as From address. Sender property is common used by mail listing provider. This property also takes effect to DKIM/DomainKeys signature, if Sender is different with From address, then you should sign DKIM/DomainKeys based on Sender domain instead of From address domain.

  • Return-Path

    This property indicates the delivery notification report address. If you don’t set this property, the Return-Path address is same as From address. This property also takes effect to SPF record, if Return-Path is different with From address, then remote SMTP server checkes SPF record of Return-Path instead of From address.

[C# - From, ReplyTo, Sender and Return-Path in Email - Example]

The following example codes demonstrate how to specify From, Reply-To, Sender and Return-Path in Email. With the following example codes:

  • If the email couldn’t be delivered to recipient, a non-delivery report will be sent to report@emailarchitect.net.
  • If the user received the email, the email client will display: sender@emailarchitect.net on behalf of from@adminsystem.com.
  • If the user click “reply”, the replied email will be sent to reply@adminsystem.com.
SmtpMail oMail = new SmtpMail("TryIt");
oMail.From = "from@adminsystem.com";
oMail.ReplyTo = "reply@adminsystem.com";
oMail.Sender = "sender@emailarchitect.net";
oMail.ReturnPath = "report@emailarchitect.net";

Mail Priority

If you want to set Higher or Lower priority to your email, you can use Priority prority

[C# - Mail Priority - Example]

// Set high priority
oMail.Priority = MailPriority.High;

Troubleshooting

When you send email in above simple C# project, if it threw an exception, please have a look at the following tips:

“No Such Host” exception

This error means DNS server cannot resolve SMTP server, you should check if you input correct server address. If your server address is correct, you should check if your DNS server setting is correct.

Common “Networking Connection” Exception

This error means there is a problem with networking connection to SMTP server. You can use Windows built-in Telnet command to detect the networking connection.

Using Telnet to detect networking connection to SMTP server

Note

Notice: in Windows 2008/Windows 8 or later version, Telnet Client is not installed by default, you should enable this command in Control Panel -> Programs and Features -> Turn Windows feature on or off -> have Telnet Client checked.

Under DOS command prompt, input “telnet [serveraddress] [port]”:

telnet mail.emailarchitect.net 25
press enter.

If the networking connection to your SMTP server is good, it should return a message like 220 .... If it returns Could not open connection to ..., that means the networking connection to SMTP server is bad, or outbound 25 port is blocked by anti-virus software, firewall or ISP. Please have a look at the following screenshot:

detect SMTP connection using telnet

SMTP 25, 587, 465 port

25 port is the default SMTP server port to receive email. However, some ISP block outbound 25 port to prevent user to send email directly to other SMTP server. Therefore, many email providers also provide an alternative port 587 to receive email from such users. 465 port is the common port used to receive email over implicit SSL connection. If you use telnet to test 465 port, it doesn’t return the “220…”, because it requires SSL hand shake. But if the connection is ok, telnet returns a flash cursor.

“5xx … IP address block or on black list or bad reputation” Exception

This error means SMTP server blocks your IP address or email content. You can try to set user/password in your codes to do user authentication and try it again. If email client set user authentication, most SMTP servers do not check client source IP address in black list.

“5xx user authenticaton” Exception

TThis error means user authentication is failed, you should check whether you input correct user/password. Password is always case-sensitive.

“5xx relay denied” Exception

For anti-spam policy, most SMTP servers do not accept the email to outbound domain without user authentication. You should set user/password in the codes and try it again.

“5xx Must issue a STARTTLS command first”

This error means SMTP server requires SSL/TLS connection. You should enable SSL/TLS connection like this:

// If your smtp server requires TLS connection, please add this line
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

“No supported authentication marshal found!”

This error means SMTP server doesn’t support user authentication or it requires user authentication over SSL/TLS connection. You can try to remove user/password in your codes and try it again.

Other error returned by SMTP server

If SMTP server returns an error, it usually returns description about this error. Some descriptions also include a HTTP link, you can go to this linked web page to learn more detail. You can also use the following codes to generate a log file to learn all SMTP session between client and server.

[C# - Using log file to detect SMTP server response - Example]

// add this line here to generate log file
oSmtp.LogFileName = "ms-appdata:///local/smtp.txt";
oSmtp.SendMail(oServer, oMail);

Next Section

In this section, I introduced how to send email in a simple C# XAML project using SMTP protocol. At next section I will introduce how to send email over SSL/TLS connection.

Send Email over SSL/TLS in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced the basic things of email sending in C#. In this section, I will introduce the SSL connection.

SSL and TLS Introduction

SSL connection encrypts data between the SMTP component and SMTP server to protects user, password and email content in TCP/IP level. Now this technology is commonly used and many SMTP servers are deployed with SSL such as Gmail, Yahoo and Hotmail. There are two ways to deploy SSL on SMTP server:

  • Explicit SSL (TLS)

    Using STARTTLS command to switch SSL channel on normal SMTP port (25 or 587);

  • Implicit SSL

    Deploying SSL on another port (465 or other port, you may query it from your server administrator

EASendMail SMTP component supports both ways. The connection can be specified by EASendMail.SmtpConnectType enumeration.

TLS 1.2

TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, and you got connection error with SSL/TLS connection, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

[C# Exmaple - SSL/TLS]

// Send email by normal TCP/IP without SSL connection
 SmtpServer oServer = new SmtpServer("localhost 25");
 oServer.ConnectType = SmtpConnectType.ConnectNormal;

 // Send email by SSL connection with STARTTLS command switching
 SmtpServer oServer = new SmtpServer("localhost 25");
 oServer.ConnectType = SmtpConnectType.ConnectSTARTTLS;

 // Send email by SSL connection with direct SSL.
 SmtpServer oServer = new SmtpServer("localhost 465");
 oServer.ConnectType = SmtpConnectType.ConnectDirectSSL;

 // Send email by SSL connection with auto-detect.
 // If port is 25 or 587, STARTTLS SSL will be used; otherwise direct SSL will be used.
 SmtpServer oServer = new SmtpServer("localhost 465");
 oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

 SmtpServer oServer = new SmtpServer("localhost 25");
 oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

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.

[C# - Send email over direct SSL on 465 port]

The following example codes demonstrate how to use EASendMail SMTP component to send email with direct SSL connection on 465 port.

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 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";

                // SMTP server requires SSL connection on 465 port, please add this line
                oServer.Port = 465;
                Server.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

[C# - Send email over TLS on 25 or 587 port]

The following example codes demonstrate how to use EASendMail SMTP component to send email with TLS (STARTTLS command) connection on 25 port. To get the full samples of EASendMail, 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 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";

                // Enable TLS connection on 25 port, please add this line
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Next Section

At next section I will introduce how to send email using Gmail account.

Send Email using Gmail in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send email over SSL connection. In this section, I will introduce how to use your Gmail account to send email in C#.

Introduction

Gmail SMTP server address is smtp.gmail.com. It requires implicit SSL or explicit SSL (TLS) connection, and you should use your Gmail email address as the user name for ESMTP authentication.

Server Port SSL/TLS
smtp.gmail.com 25, 587 TLS
smtp.gmail.com 465 SSL

Gmail App Password

To help keep your account secure, starting May 30, 2022, ​​Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

Therefore, you should sign in using App Passwords. An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on. You need to use App Password instead of the user password for user authentication.

Another solution is Gmail OAUH, please see Gmail SMTP OAUTH section.

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.

[C# - Send email using Gmail account over SSL connection on 465 port]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Gmail account.

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 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 your gmail email address
                oMail.From = new MailAddress("gmailid@gmail.com");

                // 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 using Gmail.";

                // Gmail SMTP server
                SmtpServer oServer = new SmtpServer("smtp.gmail.com");

                // User and password for ESMTP authentication
                oServer.User = "gmailid@gmail.com";

                // Create app password in Google account
                // https://support.google.com/accounts/answer/185833?hl=en
                oServer.Password = "your app password";

                // Use 465 port
                oServer.Port = 465;
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

[C# - Send email using Gmail account over TLS connection on 587 port]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Gmail account.

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 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 your gmail email address
                oMail.From = new MailAddress("gmailid@gmail.com");

                // 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 using Gmail.";

                // Gmail SMTP server
                SmtpServer oServer = new SmtpServer("smtp.gmail.com");

                // User and password for ESMTP authentication
                oServer.User = "gmailid@gmail.com";

                // Create app password in Google account
                // https://support.google.com/accounts/answer/185833?hl=en
                oServer.Password = "your app password";

                // Use 587 port
                oServer.Port = 587;
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Gmail SMTP OAUTH

The Gmail IMAP and SMTP servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Gmail Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.

Using Gmail SMTP OAUTH

Next Section

At next section I will introduce how to send email with Yahoo account.

Send Email using Yahoo in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send email using Gmail account. In this section, I will introduce how to use your Yahoo account to send email in C#.

Introduction

Yahoo SMTP server address is smtp.mail.yahoo.com. It supports both Normal/SSL connection to do user authentication, and you should use your Yahoo email address as the user name for ESMTP authentication. For example: your email is myid@yahoo.com, and then the user name should be myid@yahoo.com.

If you want to use SSL connection with Yahoo SMTP server, you must set the port to 465.

Server Port SSL/TLS
smtp.mail.yahoo.com 25, 587 TLS
smtp.mail.yahoo.com 465 SSL

Important

If you got authentication error, you need to enable Allowing less secure apps in your Yahoo account. Or you can generate App Passwords and use this app password instead of your user password.

Although Yahoo supports OAUTH, but it doesn’t provide mail permission, so OAUTH is not a solution for Yahoo mail.

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.

[C# - Send email using Yahoo account over direct SSL connection]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Yahoo account.

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 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 your yahoo email address
                oMail.From = new MailAddress("myid@yahoo.com");

                // 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 using Yahoo.";

                // Yahoo SMTP server
                SmtpServer oServer = new SmtpServer("smtp.mail.yahoo.com");

                // User and password for ESMTP authentication
                oServer.User = "myid@yahoo.com";
                oServer.Password = "testpassword";

                // Because yahoo deploys SMTP server on 465 port with direct SSL connection.
                // So we should change the port to 465.
                oServer.Port = 465;

                // detect SSL type automatically
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

[C# - Send Email using Yahoo over Explicit SSL (TLS) on 25 or 587 Port - Example]

The following example codes demonstrate how to send email using Yahoo account in C# over TLS 587 port. To get 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 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 your yahoo email address
                oMail.From = new MailAddress("myid@yahoo.com");

                // 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 using Yahoo.";

                // Yahoo SMTP server
                SmtpServer oServer = new SmtpServer("smtp.mail.yahoo.com");

                // User and password for ESMTP authentication
                oServer.User = "myid@yahoo.com";
                oServer.Password = "testpassword";

                // set 587 port
                oServer.Port = 587;

                // detect SSL type automatically
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Next Section

At next section I will introduce how to send email using Hotmail/MSN Live/Office 365 account.

Send Email using Hotmail/MSN Live/Outlook/Office365 in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send email using Yahoo account. In this section, I will introduce how to use your Hotmail/MSN Live/Outlook/Office365 account to send email in C#.

Introduction

Hotmail/MSN Live/Outlook.com SMTP server address is smtp.office365.com. It requires TLS connection to do user authentication, and you should use your Hotmail/MSN Live/Outlook.com email address as the user name for ESMTP authentication. For example: your email is liveid@hotmail.com, and then the user name should be liveid@hotmail.com.

Server Port SSL/TLS
smtp.office365.com 25, 587 TLS

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.

[C# - Send email using Hotmail/MSN Live account over TLS connection]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Hotmail/MSN Live account.

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 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 your hotmail/live/outlook.com email address
                oMail.From = new MailAddress("liveid@hotmail.com");

                // 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 using Hotmail.";

                // Hotmail SMTP server
                SmtpServer oServer = new SmtpServer("smtp.office365.com");

                // User and password for ESMTP authentication
                oServer.User = "liveid@hotmail.com";


                // If you got authentication error, try to create an app password instead of your user password.
                // https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
                oServer.Password = "your password or app password";

                // Set 587 port, if you want to use 25 port, please change 587 to 25
                oServer.Port = 587;

                // detect SSL/TLS type automatically
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Hotmail SMTP OAUTH

If your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should use SMTP OAUTH or App Password.

Microsoft Live SMTP servers (Hotmail, Oultook personal account) have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.

Using Microsoft Hotmail SMTP OAUTH

Or you can generate App Passwords and use this app password instead of your user password.

Send Email using Office 365

Office 365 SMTP server uses 587 port and explicit SSL (TLS) connection.

Server Port SSL/TLS
smtp.office365.com 25, 587 (recommended) TLS

App Password and SmtpClientAuthenticationDisabled

If your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should create an App Passwords and use this App Password instead of the user password.

You should also check if authenticated client SMTP submission (SMTP AUTH) is enabled:

Enable or disable authenticated client SMTP submission (SMTP AUTH) in Exchange Online.

[C# - Send email using Office365 account over TLS connection]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Office365 account. To get the full samples of EASendMail, 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 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 your email address
                oMail.From = new MailAddress("myid@mydomain");

                // 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 using Office365.";

                // Office365 SMTP server
                SmtpServer oServer = new SmtpServer("smtp.office365.com");

                // User and password for ESMTP authentication
                oServer.User = "myid@mydomain";


                // If you got authentication error, try to create an app password instead of your user password.
                // https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
                oServer.Password = "your password or app password";

                // use 587 port
                oServer.Port = 587;

                // detect SSL/TLS type automatically
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Office365 EWS OAUTH

If your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should use SMTP OAUTH or App Password.

Microsoft Office365 EWS/SMTP servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.

Using Microsoft Office365 EWS OAUTH

Or you can generate App Passwords and use this app password instead of your user password.

Next Section

At next section I will introduce how to send email with HTML format in C#.

Send HTML Email in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send email using Hotmail account. In this section, I will introduce how to compose and send HTML email in C#.

Introduction

If you want to specify the font, color or insert pictures in your email, you should use Html email format instead of Plain text email format.

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.

[C# - Send HTML email]

The following example codes demonstrate how to use EASendMail SMTP component to send email in HTML body format.

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 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
                oMail.Subject = "test HTML email from C# XAML project";

                // Set Html body
                oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";

                // 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;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

After you received the email by your email client, the body text is like this:

C# HTML Email - Windows Store App

Import Html to email directly

You don’t have to write the HTML source body text in your application manually. You can build a html file with HTML tools and use ImportHtmlBodyAsync method to import the html file directly.

You can also refer to the Samples_Windows8 in EASendMail Installer. Those samples demonstrate how to build a HTML email editor and send HTML email with attachment or embedded images/pictures.

c# html editor

Next Section

At next section I will introduce how to attach file attachment to email message.

Send Email with Attachment in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send HTML email. In this section, I will introduce how to add attachment to email in C#.

Introduction

To send an email with file attachment, we need to use AddAttachmentAsync method. This method can attach a file to the email message from local disk or a remote URL.

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.

[C# - Add attachment from local disk or remote URL]

The following example codes demonstrate how to use EASendMail SMTP component to send email with file attachments.

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 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
                oMail.Subject = "test email from C# XAML project with file attachment";

                // Set Html body
                oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";

                // get a file path from PicturesLibrary,
                // to access files in PicturesLibrary, you MUST have "Pictures Library" checked in
                // your project -> Package.appxmanifest -> Capabilities
                Windows.Storage.StorageFile file =
                    await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("test.jpg");

                string attfile = file.Path;
                Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);

                // if you want to add attachment from remote URL instead of local file.
                // string attfile = "http://www.emailarchitect.net/test.jpg";
                // Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);

                // you can change the Attachment name by
                // oAttachment.Name = "mytest.jpg";

                // 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;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Next Section

At next section I will introduce how to add embedded images/pictures to email message.

Send Email with Embedded Images in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send email with file attachment. In this section, I will introduce how to add embedded images to email in C#.

Introduction

To attach an embedded images to email, you should add an attachment to email at first. Then you should assign an unique identifier(contentid) to this attachment. Finally, you need to replace the <img src="your file name" /> to <img src="cid:yourcontentid" />.

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.

[C# - Add embedded images to email]

The following example codes demonstrate how to use EASendMail SMTP component to send email with embedded images.

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 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
                oMail.Subject = "test email from C# XAML project with embedded image";

                // 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;

                // get a file path from PicturesLibrary,
                // to access files in PicturesLibrary, you MUST have "Pictures Library" checked in
                // your project -> Package.appxmanifest -> Capabilities
                Windows.Storage.StorageFile file =
                    await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("test.jpg");

                string attfile = file.Path;
                Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);

                // if you want to add attachment from remote URL instead of local file.
                // string attfile = "http://www.emailarchitect.net/test.jpg";
                // Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);

                // you can change the Attachment name by
                // oAttachment.Name = "mytest.jpg";

                // Specifies the attachment as an embedded image
                string contentID = "test001@host";
                oAttachment.ContentID = contentID;
                oMail.HtmlBody = "<html><body>this is an <img src=\"cid:"
                        + contentID + "\"> embedded picture.</body></html>";

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

To attach embedded images/pictures, SmtpMail.ImportHtmlBodyAsync and SmtpMail.ImportHtmlAsync methods are strongly recommended. With these methods, you don’t have to specify the ContentID manually. The html source/file html body can be imported to email with embedded pictures automatically.

HTML editor with embedded images

You can also refer to the Samples_Windows81/10 in EASendMail Installer. Those samples demonstrate how to build a HTML email editor and send HTML email with attachment or embedded images/pictures.

c# html editor

Next Section

At next section I will introduce how to send email with event handler.

Send Email with Event Handler in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send email with embedded image. In this section, I will introduce how to send email with event handler in C#.

Introduction

In previous examples, after SendMailAsync method is invoked, if you want to know the progress of the email sending, you should use Event Handler. The following sample codes demonstrate how to use Event Handler to monitor the progress of email sending.

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.

[C# - Send email with event handler]

The following example codes demonstrate how to use EASendMail SMTP component to send email with event handler.

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;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Next Section

At next section I will introduce how to send email in asynchronous mode.

Send Email Asynchronously in C# from Windows Store Apps - XAML - UWP

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#.

Introduction

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.

[C# - Send email in asynchronous mode]

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();
        }
    }
}

Cancel Asynchronous Operation

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.

Send Email using Exchange Web Service - EWS in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send email asynchronously. In this section, I will introduce how to send email with Exchange Web Service - EWS.

Introduction

Exchange Web Services (EWS), an alternative to the MAPI protocol, is a documented SOAP based protocol introduced with Exchange Server 2007. We can use HTTP or HTTPS protocol to send email with Exchange Web Services (EWS) instead of SMTP protocol.

  • SMTP protocol

    Standard SMTP protocol based on TCP/IP, all email servers support this protocol, Exchange Server also supports SMTP protocol. Using SMTP protocol is always recommended.

  • Exchange WebDAV

    Exchange WebDAV is a set of methods based on the HTTP protocol to manage users, messages in Microsoft Exchange Server. We can use HTTP or HTTP/HTTPS protocol to send email with Exchange WebDAV instead of SMTP protocol. But since Exchange 2007, WebDAV service is disabled by default, so I only suggest that you use WebDAV protocol in Exchange 2000/2003.

  • Exchange Web Service (EWS)

    Exchange Web Services (EWS), an alternative to the MAPI protocol, is a documented SOAP based protocol introduced with Exchange Server 2007. We can use HTTP or HTTPS protocol to send email with Exchange Web Services (EWS) instead of SMTP protocol. I only suggest that you use EWS protocol in Exchange 2007/2010/2013/2016 or later version. Office365 also supports EWS very well.

With EASendMail SMTP Component, you do not have to build your EWS SOAP XML request and parse the response. It wraps the SOAP XML and HTTP request automatically. You just need to change the SmtpServer.Protocol property, and then EASendMail uses Web Service protocol to send email. Your server SHOULD be Exchange 2007 or later version; otherwise you cannot use Exchange Web Service protocol.

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.

[C# - Send email with Exchange Web Service - EWS]

The following example codes demonstrate how to use EASendMail SMTP component to send email with Exchange Web Service - EWS.

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 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 using EWS";

                // Your Exchange Server address
                SmtpServer oServer = new SmtpServer("exch.emailarchitect.net");

                // Set Exchange Web Service EWS - Exchange 2007/2010/2013/2016
                oServer.Protocol = ServerProtocol.ExchangeEWS;

                // User and password for Exchange user authentication
                oServer.User = "emailarchitect.net\\test";
                oServer.Password = "testpassword";

                // By default, Exchange Web Service requires SSL connection
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Next Section

At next section I will introduce how to send email with Exchange WebDAV.

Send Email using Exchange WebDAV in C# from Windows Store Apps - XAML - UWP

In previous section, I introduced how to send email using Exchange Web Service - EWS. In this section, I will introduce how to send email using Exchange WebDAV.

Introduction

Exchange WebDAV is a set of methods based on the HTTP protocol to manage users, messages in Microsoft Exchange Server. We can use HTTP or HTTPS protocol to send email with Exchange WebDAV instead of SMTP protocol.

  • SMTP protocol

    Standard SMTP protocol based on TCP/IP, all email servers support this protocol, Exchange Server also supports SMTP protocol. Using SMTP protocol is always recommended.

  • Exchange WebDAV

    Exchange WebDAV is a set of methods based on the HTTP protocol to manage users, messages in Microsoft Exchange Server. We can use HTTP or HTTP/HTTPS protocol to send email with Exchange WebDAV instead of SMTP protocol. But since Exchange 2007, WebDAV service is disabled by default, so I only suggest that you use WebDAV protocol in Exchange 2000/2003.

  • Exchange Web Service (EWS)

    Exchange Web Services (EWS), an alternative to the MAPI protocol, is a documented SOAP based protocol introduced with Exchange Server 2007. We can use HTTP or HTTPS protocol to send email with Exchange Web Services (EWS) instead of SMTP protocol. I only suggest that you use EWS protocol in Exchange 2007/2010/2013/2016 or later version. Office365 also supports EWS very well.

With EASendMail SMTP Component, you do not have to build your WebDAV request and parse the response. It wraps the WebDAV HTTP request automatically. You just need to change the SmtpServer.Protocol property, and then EASendMail uses WebDAV protocol to send email. Your server SHOULD be Exchange 2000 or 2003 version; otherwise you cannot use Exchange WebDAV protocol. Although Exchange 2007 still supports WebDAV protocol, but the default status of WebDAV in Exchange 2007 is disabled, so you should use Exchange Web Service protocol with Exchange 2007 or later version.

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.

[C# - Send email with Exchange WebDAV]

The following example codes demonstrate how to use EASendMail SMTP component to send email with Exchange WebDAV.

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 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 using WebDAV";

                // Your Exchange Server address
                SmtpServer oServer = new SmtpServer("exch.emailarchitect.net");

                // Set Exchange WebDAV Protocol - Exchange 2000/2003
                oServer.Protocol = ServerProtocol.ExchangeWebDav;

                // User and password for Exchange user authentication
                oServer.User = "emailarchitect.net\\test";
                oServer.Password = "testpassword";

                // If your Exchange WebDAV service requires SSL connection, please add this line
                // oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                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();
        }
    }
}

Next Section

Total sample projects in EASendMail SMTP Component installation package.

C# - UWP - SMTP, SSL, TLS, Embedded Images, EWS - Sample Projects

After you downloaded the EASendMail SMTP Component Installer and install it on your machine, there are many samples in the installation path.

All the samples locate at EASendMail Installation Folder. Most of sample projects demonstrate file attachment, embedded images, S/MIME, user authentication, SSL/TLS connection and Dns lookup.

.NET Framework Sample Projects

ASP.NET Form

C#, VB, JScript\Simple Send a simple email from ASP.NET form.
C#, VB, JScript\SimpleQueue Send email from ASP.NET to EASendMail Service.
C#, VB\Oauth Send email using Gmail and Office 365 OAUTH/XOAUTH2.
C#, VB, JScript\AdvancedQueueWithDatabase Send email from ASP.NET to EASendMail Service, background service will select recipients from database and write result back to database.

ASP.NET MVC

C#, VB\WebProject1\SimpleController Send a simple email from ASP.NET MVC by Form Post/Ajax Post.
C#, VB\WebProject1\OauthController Send email using Gmail and Office 365 OAUTH/XOAUTH2.
C#, VB\WebProject1\MassController Send mass emails using background thread pool.
C#, VB\WebProject1\DbRecipientsController Send mass emails using background thread pool, select recipients from database and write result back to database.

.NET Desktop (Windows Form)

C#, VB\Simple Send a simple email from .NET Windows Form.
C#, VB\HtmlMail Send text/html email using Web Browser Control Editor
C#, VB\HtmlMailWebView2 Send text/html email using WebView2 Control Editor
C#, VB\Mass Send mass emails using thread pool.
C#, VB\Oauth Send email using Gmail and Office365/Hotmail OAUTH/XOAUTH2.

Windows CE/PocketPC

C#, VB\pocketpc.mobile Send a simple email from .NET Compact Framework.

ActiveX Object Sample Projects

ASP Classic

VBScript, JScript\Simple Send a simple email from ASP Classic.
VBScript, JScript\SimpleQueue Send email from ASP Classic to EASendMail Service.
VBScript\Oauth Send email using Gmail and Office 365 OAUTH/XOAUTH2.
VBScript, JScript\AdvancedQueueWithDatabase Send email from ASP Classic to EASendMail Service, background service will select recipients from database and write result back to database.

Delphi

Simple Send a simple email from Delphi 7.
HtmlMail Send text/html email using Web Browser Control Editor
Mass Send mass emails using thread pool.
Oauth Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2.

MS SQL Server

SQL Send email from MS SQL Server stored procedure.

Script

VBScript/JScript/WScript Send a simple email from VBScript/JScript/WScript.

VB6

Simple Send a simple email from VB 6.0.
HtmlMail Send text/html email using Web Browser Control Editor
Mass Send mass emails using thread pool.
Oauth Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2.

VC++

Simple Send a simple email from VC++.
HtmlMail Send text/html email using Web Browser Control Editor
Mass Send mass emails using thread pool.
Oauth Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2.

Free Email Support

Not enough? Please contact our technical support team.

Support@EmailArchitect.NET

Remarks

We usually reply emails in 24hours. The reason for getting no response is likely that your smtp server bounced our reply. In this case, please try to use another email address to contact us. Your Gmail, Hotmail email account is recommended.

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.