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 VB XAML Windows Store Apps using SMTP. It also demonstrates SSL, Embedded Images, Asynchronous Mode and Multiple Threads usage.
This tutorial is for VB XAML Windows Store Apps/UWP. If you want to send email in .NET framework application, please go to Send Email in VB from .NET framework - Tutorial
Sections:
To better demonstrate how to send email using SMTP protocol, let’s create a VB XAML Windows Store App project at first, and then add the reference of EASendMail in your 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”.
The source code in MainPage.xaml is like this:
<Page
x:Class="VB_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:VB_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="42" Margin="397,140,0,0" VerticalAlignment="Top" Width="194"/>
<TextBlock Name="textStatus"
HorizontalAlignment="Left" Height="46" Margin="454,248,0,0"
TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="265"/>
</Grid>
</Page>
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.
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.
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.vb is like this:
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Sub btnSend_Click(sender As Object, e As RoutedEventArgs) Handles btnSend.Click
End Sub
End Class
Now add the following codes to the project and change From
, To
, Server
, User
and
Password
to corresponding value and compile your project.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App, do not reply"
' Your SMTP server address
Dim oServer As 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
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
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.
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.
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.
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
[VB - Email syntax]
To better understand the email address syntax, please refer to the following codes.
oMail.From = New MailAddress( "Tester", "test@adminsystem.com" )
oMail.From = New MailAddress( "Tester<test@adminsystem.com>")
oMail.From = New MailAddress( "test@adminsystem.com" )
oMail.To = New AddressCollection( "test1@adminsystem.com, test2@adminsystem.com" )
oMail.To = New AddressCollection( "Test1<test@adminsystem.com>, Test2<test2@adminsystem.com>")
oMail.To.Add( New MailAddress( "tester", "test@adminsystem.com"))
oMail.Cc.Add( New MailAddress( "CC recipient", "cc@adminsystem.com"))
oMail.Bcc.Add( New MailAddress( "Bcc recipient", "bcc@adminsystem.com"))
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.
[VB.NET - 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:
report@emailarchitect.net
.sender@emailarchitect.net
on behalf of from@adminsystem.com
.reply@adminsystem.com
.Dim oMail As New SmtpMail("TryIt")
oMail.From = "from@adminsystem.com"
oMail.ReplyTo = "reply@adminsystem.com"
oMail.Sender = "sender@emailarchitect.net"
oMail.ReturnPath = "report@emailarchitect.net"
If you want to set Higher or Lower priority to your email, you can use Priority prority
[VB - Mail Priority - Example]
' Set high priority
oMail.Priority = MailPriority.High
When you send email in above simple VB project, if it threw an exception, please have a look at the following tips:
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.
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.
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:
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.
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.
TThis error means user authentication is failed, you should check whether you input correct user/password. Password is always case-sensitive.
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.
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
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.
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.
[VB - Using log file to detect SMTP server response - Example]
Try
' add this line here to generate log file
oSmtp.LogFileName = "ms-appdata:///local/smtp.txt"
oSmtp.SendMail(oServer, oMail)
Console.WriteLine("email was sent successfully!")
Catch ep As Exception
Console.WriteLine("failed to send email with the following error:")
Console.WriteLine(ep.Message)
End Try
Next Section
In this section, I introduced how to send email in a simple VB XAML project. At next section I will introduce how to send email over SSL connection.
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.
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 VB.
Sections:
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 |
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 VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email using Gmail account.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' Set 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
oMail.Subject = "test email from VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App using Gmail."
' Gmail SMTP server address
Dim oServer As New SmtpServer("smtp.gmail.com")
' User and password for Gmail user 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
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
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.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' Set 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
oMail.Subject = "test email from VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App using Gmail."
' Gmail SMTP server address
Dim oServer As New SmtpServer("smtp.gmail.com")
' User and password for Gmail user 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
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
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.
Next Section
At next section I will introduce how to send email with Yahoo account.
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 VB.
Sections:
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 VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email using Yahoo account.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' Set 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
oMail.Subject = "test email from VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App using Yahoo."
' Yahoo SMTP server address
Dim oServer As New SmtpServer("smtp.mail.yahoo.com")
' User and password for Yahoo user 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/TLS type automatically
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
The following example codes demonstrate how to send email using Yahoo account over TLS connection on 587 port.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' Set 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
oMail.Subject = "test email from VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App using Yahoo."
' Yahoo SMTP server address
Dim oServer As New SmtpServer("smtp.mail.yahoo.com")
' User and password for Yahoo user authentication
oServer.User = "myid@yahoo.com"
oServer.Password = "testpassword"
// set 587 port
oServer.Port = 587
' detect SSL/TLS type automatically
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
Next Section
At next section I will introduce how to send email using Hotmail/MSN Live/Office 365 account.
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.com/Office365 account to send email in VB.
Sections:
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 VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to use EASendMail SMTP component to send email using Hotmail/MSN Live account. To get the full samples of EASendMail, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' Set hotmail 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
oMail.Subject = "test email from VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App using Hotmail."
' Hotmail SMTP server address
Dim oServer As New SmtpServer("smtp.office365.com")
' User and password for Hotmail 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"
' Enable TLS connection on 25 port, please add this line
oServer.Port = 25
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
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.
Office 365 SMTP server uses 587 port and explicit SSL (TLS) connection.
Server | Port | SSL/TLS |
smtp.office365.com | 25, 587 (recommended) | TLS |
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.
The following example codes demonstrate how to send email using Office 365 account.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' Set hotmail 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
oMail.Subject = "test email from VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App using Office365."
' Office365 SMTP server address
Dim oServer As New SmtpServer("smtp.office365.com")
' User and password for Office365 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"
' Enable TLS connection on 587 port
oServer.Port = 587
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
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 VB.
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 VB.
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 VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email in HTML body format.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB 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
Dim oServer As 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
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
After you received the email by your email client, the body text is like this:
Of course, 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_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.
Next Section
At next section I will introduce how to attach file attachment to email message.
In previous section, I introduced how to send HTML email. In this section, I will introduce how to add attachment to email in VB.
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 VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email with file attachments.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB XAML project"
// 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
Dim file As Windows.Storage.StorageFile =
Await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("test.jpg")
Dim attfile As String = file.Path
Dim oAttachment As Attachment = Await oMail.AddAttachmentAsync(attfile)
' if you want to add attachment from remote URL instead of local file.
' Dim attfile As String = "http://www.emailarchitect.net/test.jpg"
' Dim oAttachment As Attachment = Await oMail.AddAttachmentAsync(attfile)
' you can change the Attachment name by
' oAttachment.Name = "mytest.jpg"
' Your SMTP server address
Dim oServer As 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
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
Next Section
At next section I will introduce how to add embedded images/pictures to email message.
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 VB.
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 VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email with embedded images.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB XAML project"
' get a file path from PicturesLibrary,
' to access files in PicturesLibrary, you MUST have "Pictures Library" checked in
' your project -> Package.appxmanifest -> Capabilities
Dim file As Windows.Storage.StorageFile =
Await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("test.jpg")
Dim attfile As String = file.Path
Dim oAttachment As Attachment = Await oMail.AddAttachmentAsync(attfile)
' if you want to add attachment from remote URL instead of local file.
' Dim attfile As String = "http://www.emailarchitect.net/test.jpg"
' Dim oAttachment As Attachment = Await oMail.AddAttachmentAsync(attfile)
' you can change the Attachment name by
' oAttachment.Name = "mytest.jpg"
' Specifies the attachment as an embedded image
Dim contentID As String = "test001@host"
oAttachment.ContentID = contentID
oMail.HtmlBody = "<html><body>this is an <img src=""cid:" +
contentID + """> embedded picture.</body></html>"
' Your SMTP server address
Dim oServer As 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
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
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.
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.
Next Section
At next section I will introduce how to send email with event handler.
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 VB.
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 VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email with event handler.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Sub OnSecuring(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Securing ... "
textStatus.Text = status
End Sub
Private Sub OnAuthorized(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Authorized"
textStatus.Text = status
End Sub
Public Sub OnConnected(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Connected"
textStatus.Text = status
End Sub
Public Sub OnSendingDataStream(sender As Object, e As SmtpDataStreamEventArgs)
Dim status As String = [String].Format("{0}/{1} sent", e.Sent, e.Total)
textStatus.Text = status
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App, do not reply"
' Your SMTP server address
Dim oServer As 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
Dim oSmtp As New SmtpClient()
' Add event handlers
AddHandler oSmtp.Authorized, AddressOf OnAuthorized
AddHandler oSmtp.Connected, AddressOf OnConnected
AddHandler oSmtp.Securing, AddressOf OnSecuring
AddHandler oSmtp.SendingDataStream, AddressOf OnSendingDataStream
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
Next Section
At next section I will introduce how to send email in asynchronous mode.
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 VB.
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 VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email in asynchronous mode.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Sub OnSecuring(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Securing ... "
textStatus.Text = status
End Sub
Private Sub OnAuthorized(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Authorized"
textStatus.Text = status
End Sub
Public Sub OnConnected(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Connected"
textStatus.Text = status
End Sub
Public Sub OnSendingDataStream(sender As Object, e As SmtpDataStreamEventArgs)
Dim status As String = [String].Format("{0}/{1} sent", e.Sent, e.Total)
textStatus.Text = status
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App, do not reply"
' Your SMTP server address
Dim oServer As 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
Dim oSmtp As New SmtpClient()
' Add event handlers
AddHandler oSmtp.Authorized, AddressOf OnAuthorized
AddHandler oSmtp.Connected, AddressOf OnConnected
AddHandler oSmtp.Securing, AddressOf OnSecuring
AddHandler oSmtp.SendingDataStream, AddressOf OnSendingDataStream
' get a asynchronous action object
Dim asyncObj As IAsyncAction = 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 ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
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="VB_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:VB_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="42" Margin="397,140,0,0" VerticalAlignment="Top" Width="194"/>
<TextBlock Name="textStatus"
HorizontalAlignment="Left" Height="46" Margin="454,248,0,0"
TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="265"/>
<Button Content="Button" Name="btnCancel" HorizontalAlignment="Left"
Height="56" Margin="816,169,0,0" VerticalAlignment="Top" Width="199"/>
</Grid>
</Page>
Source codes in MainPage.xaml.vb
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
' Declare asynchronous action object
Private asyncCancel As IAsyncAction = Nothing
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Sub OnSecuring(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Securing ... "
textStatus.Text = status
End Sub
Private Sub OnAuthorized(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Authorized"
textStatus.Text = status
End Sub
Public Sub OnConnected(sender As Object, e As SmtpStatusEventArgs)
Dim status As String = e.Status
' status = "Connected"
textStatus.Text = status
End Sub
Public Sub OnSendingDataStream(sender As Object, e As SmtpDataStreamEventArgs)
Dim status As String = [String].Format("{0}/{1} sent", e.Sent, e.Total)
textStatus.Text = status
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
asyncCancel = Nothing
btnSend.IsEnabled = True
btnCancel.IsEnabled = False
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App, do not reply"
' Your SMTP server address
Dim oServer As 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
Dim oSmtp As New SmtpClient()
' Add event handlers
AddHandler oSmtp.Authorized, AddressOf OnAuthorized
AddHandler oSmtp.Connected, AddressOf OnConnected
AddHandler oSmtp.Securing, AddressOf OnSecuring
AddHandler oSmtp.SendingDataStream, AddressOf 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 ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
' Cancel email sending
Private Sub btnCancel_Click(sender As Object, e As RoutedEventArgs) Handles btnCancel.Click
btnCancel.IsEnabled = False
If (asyncCancel IsNot Nothing) Then
asyncCancel.Cancel()
End If
End Sub
End Class
Next Section
At next section I will introduce how to send email using Exchange Web Service - EWS.
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.
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.
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.
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.
Note
Remarks: All of samples in this section are based on first section: Send email in A simple VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email with Exchange Web Service - EWS.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App using EWS"
' Your Exchange server address
Dim oServer As New SmtpServer("exch.emailarchitect.net")
' Set Exchange Web Service protocol - Exchange 2007/2010/2013/2016
oServer.Protocol = ServerProtocol.ExchangeEWS
' Exchange User authentication
oServer.User = "emailarchitect.net\test"
oServer.Password = "administratorpassword"
' Exchange EWS Service requires SSL connection by default
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
Next Section
At next section I will introduce how to send email with Exchange WebDAV.
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.
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.
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.
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.
Note
Remarks: All of samples in this section are based on first section: Send email in A simple VB XAML Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.
The following example codes demonstrate how to send email with Exchange WebDAV.
Note
To get the full sample projects, please refer to Samples section.
' Add EASendMail and Tasks Namespace
Imports EASendMail
Imports System.Threading.Tasks
Public NotInheritable Class MainPage
Inherits Page
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
End Sub
Private Async Function btnSend_Click(sender As Object, e As RoutedEventArgs) _
As Task Handles btnSend.Click
btnSend.IsEnabled = False
Await Send_Email()
btnSend.IsEnabled = True
End Function
Private Async Function Send_Email() As Task
Dim Result As String = ""
Try
Dim oMail As New SmtpMail("TryIt")
' 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 VB XAML project"
' Set email body
oMail.TextBody = "this is a test email sent from Windows Store App using EWS"
' Your Exchange server address
Dim oServer As New SmtpServer("exch.emailarchitect.net")
' Set Exchange Web Service protocol - Exchange 2007/2010/2013
oServer.Protocol = ServerProtocol.ExchangeEWS
' Exchange User authentication
oServer.User = "emailarchitect.net\test"
oServer.Password = "administratorpassword"
' Exchange EWS Service requires SSL connection by default
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
Dim oSmtp As New SmtpClient()
Await oSmtp.SendMailAsync(oServer, oMail)
Result = "Email was sent successfully!"
Catch ep As Exception
Result = String.Format("Failed to send email with the following error: {0}", ep.Message)
End Try
' Display Result by Diaglog box
Dim dlg As New Windows.UI.Popups.MessageDialog(Result)
Await dlg.ShowAsync()
End Function
End Class
Next Section
Total sample projects in EASendMail SMTP Component installation package.
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.
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. |
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. |
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. |
C#, VB\pocketpc.mobile | Send a simple email from .NET Compact Framework. |
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. |
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. |
SQL | Send email from MS SQL Server stored procedure. |
VBScript/JScript/WScript | Send a simple email from VBScript/JScript/WScript. |
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. |
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.
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.