Send Email Asynchronously in VB 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 VB.

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

[VB - Send email in asynchronous mode]

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

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="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.

Appendix

Comments

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