Sending Email using WPF and C#

Introduction

In this article you will learn how to send email from you WPF application using C#.Sending email from your WPF application is actually very simple.You can send email using SMTP Server that require authentication and SSL.You can use GMail's SMTP server (smtp.gmail.com) to send Email.You will also need the SMTP Server's port Number(For GMail: 587).Another thing, you are using GMail, so you need EnableSsl to be set to true, because GMail needs secure authentication to send email.I have made a Email Class (WPFEmailer.cs) that can use from both Windows Form and WPF application.I want to share it with all of you.

Using the Code

If you go through the code, you will see that i have import the System.Net.Mail namespace.The System.Net.Mail namespace contains the SmtpClient and MailMessage Classes that we need in order to send the email.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Threading;


namespace EmailSendWPF
{
    /// <summary>
    /// WPF Email Class
    /// </summary>
    class WPFEmailer
    {
        public string From = string.Empty;
        public string To = string.Empty;
        public string User = string.Empty;
        public string Password = string.Empty;
        public string Subject = string.Empty;
        public string Body = string.Empty;
        public string AttachmentPath = string.Empty;
        public string Host = "127.0.0.1";
        public int Port = 25;
        public string CC = string.Empty;
        public bool IsHtml = false;
        public int SendUsing = 0;//0 = Network, 1 = PickupDirectory, 2 = SpecifiedPickupDirectory
        public bool UseSSL=true;
        public int AuthenticationMode=1;//0 = No authentication, 1 = Plain Text, 2 = NTLM authentication
        
        public WPFEmailer()
        {
            
        }
       
        public void SendEmail()
        {
            new Thread(new ThreadStart(SendMessage)).Start();
        }
        /// <summary>
        /// Send Email Message method.
        /// </summary>
        private void SendMessage()
        {
            try
            {
                MailMessage oMessage = new MailMessage();
                SmtpClient smtpClient = new SmtpClient(Host);
            
                oMessage.From = new MailAddress(From);
                oMessage.To.Add(To);
                oMessage.Subject = Subject;
                oMessage.IsBodyHtml = IsHtml; 
                oMessage.Body = Body;

                if (CC != string.Empty)                   
                    oMessage.CC.Add(CC);
                            
                switch (SendUsing)
                { 
                    case 0:
                        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                        break;
                    case 1:
                        smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                        break;
                    case 2:
                        smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                        break;
                    default :
                        smtpClient.DeliveryMethod=SmtpDeliveryMethod.Network;
                        break;
                
                }            
                if(AuthenticationMode > 0)
                {
                    smtpClient.Credentials = new NetworkCredential(User,Password);
                }                            
                
                smtpClient.Port = Port;
                smtpClient.EnableSsl = UseSSL;

                // Create and add the attachment
                if(AttachmentPath!=string.Empty)
                {                    
                    oMessage.Attachments.Add(new Attachment(AttachmentPath));
                }

                try
                {
                    // Deliver the message    
                    smtpClient.Send(oMessage);                    
                    
                }
                
                catch( Exception ex )
                {
                    ex.ToString();
                    
                }                
            }
            catch(Exception ex)
            {
                ex.ToString();
            }
        }

    }
}

From the above WPFEmailer.cs you see that there are some property that is useful for email sending application.Using this class you can send Text or HTML email. You can attached file by specifying AttachmentPath property as the path of the attached file that you want to send with your email. You have to specify all the property like User, Password, From, To , Host (SMTP Server Name), Port (Port Number), IsHtml and UseSSL as true or false.

You can use this class in your application to send email. You can use it in both WPF and Windows application. In this article i will show you how can you use it to send email from WPF application.

 

Example use

I have use a WPF application to send email.The Windows Presentation Foundation (or WPF), formerly code-named Avalon, is a graphical subsystem in .NET Framework 3.0, which uses a markup language, known as XAML for rich user interface development.

 

WPFEmailer

 

The XAML code of the application is very simple but i want to share one thing with the beginner of WPF is that the TextBox doesn't have a password mode. Instead, there's a special control for this: PasswordBox.Use PasswordBox control and set PasswordChar as '*'

 

<Window x:Class="EmailSendWPF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF Emailer" Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="122*" />
            <ColumnDefinition Width="156*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="227*" />
            <RowDefinition Height="35*" />
        </Grid.RowDefinitions>
        <Button Name="btnSendEmail"  Grid.Column="1" Grid.Row="1" Height="23" VerticalAlignment="Top" HorizontalAlignment="Left" Width="74" Click="btnSendEmail_Click">Send Email</Button>
        <StackPanel Name="stackPanel1" >
            <Label Height="28" Name="label1" Width="auto" HorizontalAlignment="Right">Mail From</Label>
            <Label Height="28" Name="label2" Width="auto" HorizontalAlignment="Right">Password</Label>
            <Label Height="28" Name="label3" Width="auto" HorizontalAlignment="Right">Mail To</Label>
            <Label Height="28" Name="label4" Width="auto" HorizontalAlignment="Right">SMTP Server Name</Label>
            <Label Height="28" Name="label5" Width="auto" HorizontalAlignment="Right">SMTP Port Number</Label>
            <Label Height="28" Name="label6" Width="auto" HorizontalAlignment="Right">Subject</Label>
            <Label Height="28" Name="label7" Width="auto" HorizontalAlignment="Right">Body</Label>
        </StackPanel>
        <StackPanel Grid.Column="1" Name="stackPanel2">
            <TextBox Height="20" Name="txtUserName" Width="auto" Margin="0,6,6,3" ToolTip="Example: yourmail@gmail.com" />
            <PasswordBox Height="20" Name="txtPassword" Width="auto" Margin="0,3,6,3" PasswordChar="*" ToolTip="Your Password." />
            <TextBox Height="20" Name="txtTo" Width="auto" Margin="0,6,6,3" ToolTip="Example: SendTo@yahoo.com" />
            <TextBox Height="20" Name="txtSMTPServerName" Width="auto" Margin="0,5,6,3" ToolTip="Example: smtp.gmail.com" />
            <TextBox Height="20" Name="txtSMTPPortNumber" Width="auto" Margin="0,3,6,3" ToolTip="Example: For gmail is 587" />
            <TextBox Height="20" Name="txtSubject" Width="auto" Margin="0,5,6,3" ToolTip="Email Subject!" />
            <TextBox Height="53" Name="txtBody" Width="auto" Margin="0,3,6,6"
                     TextWrapping="Wrap" ToolTip="Eamil Body Here!" />
            
        </StackPanel>
        <Button Grid.Column="1" Margin="78,0,0,0" Name="btnCancel" Grid.Row="1" HorizontalAlignment="Left" Width="74" Height="23" VerticalAlignment="Top" Click="btnCancel_Click">Cancel</Button>
    </Grid>
</Window>

Use the following code to send email using WPFEmailer.cs Class.

 

private void btnSendEmail_Click(object sender, RoutedEventArgs e)
        {
            WPFEmailer wpfEmailer = new WPFEmailer();
            wpfEmailer.User = txtUserName.Text;
            wpfEmailer.Password = txtPassword.Password;
            wpfEmailer.From = txtUserName.Text;
            wpfEmailer.To = txtTo.Text;
            wpfEmailer.Host = txtSMTPServerName.Text;
            wpfEmailer.Port = Convert.ToInt32(txtSMTPPortNumber.Text);
            wpfEmailer.Subject = txtSubject.Text;
            wpfEmailer.Body = txtBody.Text;
            try
            {
                wpfEmailer.SendEmail();
                MessageBox.Show("Message send successfully.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:"+ex.ToString());
            }
        }
You can do many things using this WPFEmailer.cs Class.

If you want to send HTML page as Email then just set the IsHtml property of the WPFEmailer.cs class as True. If you want to attach a file with the email then just attached the path of the file to the AttachmentPath property. That's all.

Isn't it easy? So enjoy sending email. If you have any question just send me email or post your comments. Thank you.

Published 03-23-2009 1:59 AM by MD.ZAHIDUL ISLAM

Comments

# re: Sending Email using WPF and C#

Saturday, March 28, 2009 5:15 AM by Shaoun

What will happen if we want to send an image as image resource?

# re: Sending Email using WPF and C#

Saturday, March 28, 2009 5:16 AM by Shaoun

What will happen if we want to send an image as image resource?

# re: Sending Email using WPF and C#

Monday, March 30, 2009 1:45 PM by Md Nazmul Ahsan

You can attached the image file as email attachment using following code line.

==========================================================

oMessage.Attachments.Add(new Attachment([Attachment Path]));

==========================================================

# re: Sending Email using WPF and C#

Monday, March 30, 2009 2:41 PM by MD.ZAHIDUL ISLAM

If you check the WPFEmailer Class closely, you will find AttachmentPath where you have to specify the path of your image resource.

If you want to send "test.gif" image, you have to write the following code:

.....................................................

wpfEmailer.Attachments.Add(new

                 Attachment("c:\\test.gif"));

.....................................................

Enjoy sending Email.Thank you.

# re: Sending Email using WPF and C#

Friday, April 03, 2009 3:58 AM by Shaoun

Hello, Thanks for your reply. I am not talking about adding attachment. I am talking about sending image as an embedded image. You have to create the message content in multiple view. That is plain text view and HTML view. Then you have to create a linked resource and add that to the HTML view. Combine them and send it. Here is the code:

Dim plainView as New AlternateView= AlternateView.CreateAlternateViewFromString("Plain text part can be viewed by those clients that don't support html", null, "text/plain")

Dim htmlview as New AlternateView=AlternateView.CreateAlternateViewFromString("Here is an embedded image."", null, "text/html")

Dim logo as new LinkedResource = LinkedResource( "c:\temp\companylogo.gif" )

logo.ContentId = "logo"

htmlView.LinkedResources.Add(logo)

mail.AlternateViews.Add(plainView)

mail.AlternateViews.Add(htmlView)

That is the correct way of sending embedded images. Also, it has a great advantages. If some client is unable to view the HTML part then .net mail class will deliver the plain text part. Thank you.

# re: Sending Email using WPF and C#

Friday, April 03, 2009 5:30 AM by MD.ZAHIDUL ISLAM

Thank you Shaoun for your comments and demo code.

Powered by Community Server (Non-Commercial Edition), by Telligent Systems