.Net application development specialists
asp.net, c#, vb.net, html, javascript, jquery, html, xhtml, css, oop, design patterns, sql server, mvc and much more
contact: admin@paxium.co.uk

Paxium is the company owned by myself, Dave Amour and used for providing IT contract development services including


  • Application development - Desktop, Web, Services - with Classic ASP, Asp.net WebForms, Asp.net MVC, Asp.net Core
  • Html, Css, JavaScript, jQuery, React, C#, SQL Server, Ado.net, Entity Framework, NHibernate, TDD, WebApi, GIT, IIS
  • Database schema design, implementation & ETL activities
  • Website design and hosting including email hosting
  • Training - typically one to one sessions
  • Reverse Engineering and documentation of undocumented systems
  • Code Reviews
  • Performance Tuning
  • Located in Cannock, Staffordshire
Rugeley Chess Club Buying Butler Cuckooland Katmaid Pet Sitting Services Roland Garros 60 60 Golf cement Technical Conformity Goofy MaggieBears Vacc Track Find Your Smart Phone eBate Taylors Poultry Services Lafarge Rebates System Codemasters Grid Game eBate DOFF

Sending Email with C#

Sending emails is a very common requirement within modern applications.  In particular web based application send many emails in relation to registration and alerts of various kinds.

In this article we are going to build a simple WinForms application to send emails.  The code can easily be applied to an asp.net application just by changing the GUI part - the underlying fundamental C# code would be the same.

This article has been written with Visual studio 2008 in mind so first fire up Visual Studio and create a new WinForms C# project with an appropriate name.

We now need to layout all of the controls on our form which will look like this:

Email Sender Form

 If you can't be bothered to do all this then feel free to employ your copy and paste skills with the code below which is from my designer file: 

namespace EmailSender
{
    partial class EmailForm
    {
        ///<summary>
        /// Required designer variable.
        ///</summary>
        private System.ComponentModel.IContainer components = null;
 
        ///<summary>
        /// Clean up any resources being used.
        ///</summary>
        ///<param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #region Windows Form Designer generated code
 
        ///<summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        ///</summary>
        private void InitializeComponent()
        {
            this.To = new System.Windows.Forms.TextBox();
            this.From = new System.Windows.Forms.TextBox();
            this.Subject = new System.Windows.Forms.TextBox();
            this.Body = new System.Windows.Forms.TextBox();
            this.Send = new System.Windows.Forms.Button();
            this.ToLabel = new System.Windows.Forms.Label();
            this.FromLabel = new System.Windows.Forms.Label();
            this.SubjectLabel = new System.Windows.Forms.Label();
            this.BodyLabel = new System.Windows.Forms.Label();
            this.SMTPserverLabel = new System.Windows.Forms.Label();
            this.SMTPServer = new System.Windows.Forms.TextBox();
            this.UsernameLabel = new System.Windows.Forms.Label();
            this.Username = new System.Windows.Forms.TextBox();
            this.PasswordLabel = new System.Windows.Forms.Label();
            this.Password = new System.Windows.Forms.TextBox();
            this.UseAuthenticationLabel = new System.Windows.Forms.Label();
            this.UseAuthentication = new System.Windows.Forms.CheckBox();
            this.EmailDetailsGroupBox = new System.Windows.Forms.GroupBox();
            this.EmailFormat = new System.Windows.Forms.ComboBox();
            this.FormatLabel = new System.Windows.Forms.Label();
            this.AddAttachment = new System.Windows.Forms.Button();
            this.AttachmentPath = new System.Windows.Forms.TextBox();
            this.AttachmentLabel = new System.Windows.Forms.Label();
            this.ServerDetailsGroupBox = new System.Windows.Forms.GroupBox();
            this.EmailDetailsGroupBox.SuspendLayout();
            this.ServerDetailsGroupBox.SuspendLayout();
            this.SuspendLayout();
            //
            // To
            //
            this.To.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.To.Location = new System.Drawing.Point(117, 30);
            this.To.Name = "To";
            this.To.Size = new System.Drawing.Size(319, 24);
            this.To.TabIndex = 0;
            //
            // From
            //
            this.From.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.From.Location = new System.Drawing.Point(117, 60);
            this.From.Name = "From";
            this.From.Size = new System.Drawing.Size(319, 24);
            this.From.TabIndex = 1;
            //
            // Subject
            //
            this.Subject.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Subject.Location = new System.Drawing.Point(117, 90);
            this.Subject.Name = "Subject";
            this.Subject.Size = new System.Drawing.Size(197, 24);
            this.Subject.TabIndex = 2;
            //
            // Body
            //
            this.Body.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Body.Location = new System.Drawing.Point(117, 170);
            this.Body.Multiline = true;
            this.Body.Name = "Body";
            this.Body.Size = new System.Drawing.Size(462, 85);
            this.Body.TabIndex = 3;
            //
            // Send
            //
            this.Send.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Send.Location = new System.Drawing.Point(346, 511);
            this.Send.Name = "Send";
            this.Send.Size = new System.Drawing.Size(96, 30);
            this.Send.TabIndex = 4;
            this.Send.Text = "SendEmail";
            this.Send.UseVisualStyleBackColor = true;
            this.Send.Click += new System.EventHandler(this.Send_Click);
            //
            // ToLabel
            //
            this.ToLabel.AutoSize = true;
            this.ToLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.ToLabel.Location = new System.Drawing.Point(75, 30);
            this.ToLabel.Name = "ToLabel";
            this.ToLabel.Size = new System.Drawing.Size(26, 18);
            this.ToLabel.TabIndex = 5;
            this.ToLabel.Text = "To";
            //
            // FromLabel
            //
            this.FromLabel.AutoSize = true;
            this.FromLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.FromLabel.Location = new System.Drawing.Point(57, 60);
            this.FromLabel.Name = "FromLabel";
            this.FromLabel.Size = new System.Drawing.Size(44, 18);
            this.FromLabel.TabIndex = 6;
            this.FromLabel.Text = "From";
            //
            // SubjectLabel
            //
            this.SubjectLabel.AutoSize = true;
            this.SubjectLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.SubjectLabel.Location = new System.Drawing.Point(44, 93);
            this.SubjectLabel.Name = "SubjectLabel";
            this.SubjectLabel.Size = new System.Drawing.Size(57, 18);
            this.SubjectLabel.TabIndex = 7;
            this.SubjectLabel.Text = "Subject";
            //
            // BodyLabel
            //
            this.BodyLabel.AutoSize = true;
            this.BodyLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BodyLabel.Location = new System.Drawing.Point(59, 170);
            this.BodyLabel.Name = "BodyLabel";
            this.BodyLabel.Size = new System.Drawing.Size(42, 18);
            this.BodyLabel.TabIndex = 8;
            this.BodyLabel.Text = "Body";
            //
            // SMTPserverLabel
            //
            this.SMTPserverLabel.AutoSize = true;
            this.SMTPserverLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.SMTPserverLabel.Location = new System.Drawing.Point(44, 38);
            this.SMTPserverLabel.Name = "SMTPserverLabel";
            this.SMTPserverLabel.Size = new System.Drawing.Size(97, 18);
            this.SMTPserverLabel.TabIndex = 10;
            this.SMTPserverLabel.Text = "SMTP Server";
            //
            // SMTPServer
            //
            this.SMTPServer.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.SMTPServer.Location = new System.Drawing.Point(157, 35);
            this.SMTPServer.Name = "SMTPServer";
            this.SMTPServer.Size = new System.Drawing.Size(319, 24);
            this.SMTPServer.TabIndex = 9;
            //
            // UsernameLabel
            //
            this.UsernameLabel.AutoSize = true;
            this.UsernameLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.UsernameLabel.Location = new System.Drawing.Point(64, 68);
            this.UsernameLabel.Name = "UsernameLabel";
            this.UsernameLabel.Size = new System.Drawing.Size(77, 18);
            this.UsernameLabel.TabIndex = 12;
            this.UsernameLabel.Text = "Username";
            //
            // Username
            //
            this.Username.Enabled = false;
            this.Username.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Username.Location = new System.Drawing.Point(157, 65);
            this.Username.Name = "Username";
            this.Username.Size = new System.Drawing.Size(197, 24);
            this.Username.TabIndex = 11;
            //
            // PasswordLabel
            //
            this.PasswordLabel.AutoSize = true;
            this.PasswordLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.PasswordLabel.Location = new System.Drawing.Point(64, 98);
            this.PasswordLabel.Name = "PasswordLabel";
            this.PasswordLabel.Size = new System.Drawing.Size(75, 18);
            this.PasswordLabel.TabIndex = 14;
            this.PasswordLabel.Text = "Password";
            //
            // Password
            //
            this.Password.Enabled = false;
            this.Password.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Password.Location = new System.Drawing.Point(157, 95);
            this.Password.Name = "Password";
            this.Password.Size = new System.Drawing.Size(197, 24);
            this.Password.TabIndex = 13;
            //
            // UseAuthenticationLabel
            //
            this.UseAuthenticationLabel.AutoSize = true;
            this.UseAuthenticationLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.UseAuthenticationLabel.Location = new System.Drawing.Point(505, 41);
            this.UseAuthenticationLabel.Name = "UseAuthenticationLabel";
            this.UseAuthenticationLabel.Size = new System.Drawing.Size(131, 18);
            this.UseAuthenticationLabel.TabIndex = 15;
            this.UseAuthenticationLabel.Text = "Use Authentication";
            //
            // UseAuthentication
            //
            this.UseAuthentication.AutoSize = true;
            this.UseAuthentication.Location = new System.Drawing.Point(642, 44);
            this.UseAuthentication.Name = "UseAuthentication";
            this.UseAuthentication.Size = new System.Drawing.Size(15, 14);
            this.UseAuthentication.TabIndex = 16;
            this.UseAuthentication.UseVisualStyleBackColor = true;
            this.UseAuthentication.CheckedChanged += new System.EventHandler(this.UseAuthentication_CheckedChanged);
            //
            // EmailDetailsGroupBox
            //
            this.EmailDetailsGroupBox.Controls.Add(this.EmailFormat);
            this.EmailDetailsGroupBox.Controls.Add(this.FormatLabel);
            this.EmailDetailsGroupBox.Controls.Add(this.AddAttachment);
            this.EmailDetailsGroupBox.Controls.Add(this.AttachmentPath);
            this.EmailDetailsGroupBox.Controls.Add(this.AttachmentLabel);
            this.EmailDetailsGroupBox.Controls.Add(this.BodyLabel);
            this.EmailDetailsGroupBox.Controls.Add(this.SubjectLabel);
            this.EmailDetailsGroupBox.Controls.Add(this.FromLabel);
            this.EmailDetailsGroupBox.Controls.Add(this.ToLabel);
            this.EmailDetailsGroupBox.Controls.Add(this.Body);
            this.EmailDetailsGroupBox.Controls.Add(this.Subject);
            this.EmailDetailsGroupBox.Controls.Add(this.From);
            this.EmailDetailsGroupBox.Controls.Add(this.To);
           this.EmailDetailsGroupBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.EmailDetailsGroupBox.Location = new System.Drawing.Point(41, 19);
            this.EmailDetailsGroupBox.Name = "EmailDetailsGroupBox";
            this.EmailDetailsGroupBox.Size = new System.Drawing.Size(694, 315);
            this.EmailDetailsGroupBox.TabIndex = 17;
            this.EmailDetailsGroupBox.TabStop = false;
            this.EmailDetailsGroupBox.Text = "Email Details";
            //
            // EmailFormat
            //
            this.EmailFormat.FormattingEnabled = true;
            this.EmailFormat.Items.AddRange(new object[] {
            "",
            "Text",
            "HTML"});
            this.EmailFormat.Location = new System.Drawing.Point(117, 270);
            this.EmailFormat.Name = "EmailFormat";
            this.EmailFormat.Size = new System.Drawing.Size(121, 26);
            this.EmailFormat.TabIndex = 21;
            //
            // FormatLabel
            //
            this.FormatLabel.AutoSize = true;
            this.FormatLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.FormatLabel.Location = new System.Drawing.Point(44, 270);
            this.FormatLabel.Name = "FormatLabel";
            this.FormatLabel.Size = new System.Drawing.Size(56, 18);
            this.FormatLabel.TabIndex = 20;
            this.FormatLabel.Text = "Format";
            //
            // AddAttachment
            //
            this.AddAttachment.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.AddAttachment.Location = new System.Drawing.Point(501, 131);
            this.AddAttachment.Name = "AddAttachment";
            this.AddAttachment.Size = new System.Drawing.Size(78, 24);
            this.AddAttachment.TabIndex = 19;
            this.AddAttachment.Text = "Browse";
            this.AddAttachment.UseVisualStyleBackColor = true;
            this.AddAttachment.Click += new System.EventHandler(this.AddAttachment_Click);
            //
            // AttachmentPath
            //
            this.AttachmentPath.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.AttachmentPath.Location = new System.Drawing.Point(117, 131);
            this.AttachmentPath.Name = "AttachmentPath";
            this.AttachmentPath.Size = new System.Drawing.Size(378, 24);
            this.AttachmentPath.TabIndex = 10;
            //
            // AttachmentLabel
            //
            this.AttachmentLabel.AutoSize = true;
            this.AttachmentLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.AttachmentLabel.Location = new System.Drawing.Point(19, 134);
            this.AttachmentLabel.Name = "AttachmentLabel";
            this.AttachmentLabel.Size = new System.Drawing.Size(82, 18);
            this.AttachmentLabel.TabIndex = 9;
            this.AttachmentLabel.Text = "Attachment";
            //
            // ServerDetailsGroupBox
            //
            this.ServerDetailsGroupBox.Controls.Add(this.UseAuthentication);
            this.ServerDetailsGroupBox.Controls.Add(this.UseAuthenticationLabel);
            this.ServerDetailsGroupBox.Controls.Add(this.PasswordLabel);
            this.ServerDetailsGroupBox.Controls.Add(this.Password);
            this.ServerDetailsGroupBox.Controls.Add(this.UsernameLabel);
            this.ServerDetailsGroupBox.Controls.Add(this.Username);
            this.ServerDetailsGroupBox.Controls.Add(this.SMTPserverLabel);
            this.ServerDetailsGroupBox.Controls.Add(this.SMTPServer);
            this.ServerDetailsGroupBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.ServerDetailsGroupBox.Location = new System.Drawing.Point(41, 353);
            this.ServerDetailsGroupBox.Name = "ServerDetailsGroupBox";
            this.ServerDetailsGroupBox.Size = new System.Drawing.Size(695, 140);
            this.ServerDetailsGroupBox.TabIndex = 18;
            this.ServerDetailsGroupBox.TabStop = false;
            this.ServerDetailsGroupBox.Text = "Server Details";
            //
            // EmailForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(758, 553);
            this.Controls.Add(this.ServerDetailsGroupBox);
            this.Controls.Add(this.EmailDetailsGroupBox);
            this.Controls.Add(this.Send);
            this.Name = "EmailForm";
            this.Text = "Email Sender";
            this.EmailDetailsGroupBox.ResumeLayout(false);
            this.EmailDetailsGroupBox.PerformLayout();
            this.ServerDetailsGroupBox.ResumeLayout(false);
            this.ServerDetailsGroupBox.PerformLayout();
            this.ResumeLayout(false);
 
        }
 
        #endregion
 
        private System.Windows.Forms.TextBox To;
        private System.Windows.Forms.TextBox From;
        private System.Windows.Forms.TextBox Subject;
        private System.Windows.Forms.TextBox Body;
        private System.Windows.Forms.Button Send;
        private System.Windows.Forms.Label ToLabel;
        private System.Windows.Forms.Label FromLabel;
        private System.Windows.Forms.Label SubjectLabel;
        private System.Windows.Forms.Label BodyLabel;
        private System.Windows.Forms.Label SMTPserverLabel;
        private System.Windows.Forms.TextBox SMTPServer;
        private System.Windows.Forms.Label UsernameLabel;
        private System.Windows.Forms.TextBox Username;
        private System.Windows.Forms.Label PasswordLabel;
        private System.Windows.Forms.TextBox Password;
        private System.Windows.Forms.Label UseAuthenticationLabel;
        private System.Windows.Forms.CheckBox UseAuthentication;
        private System.Windows.Forms.GroupBox EmailDetailsGroupBox;
        private System.Windows.Forms.GroupBox ServerDetailsGroupBox;
        private System.Windows.Forms.Button AddAttachment;
        private System.Windows.Forms.TextBox AttachmentPath;
        private System.Windows.Forms.Label AttachmentLabel;
        private System.Windows.Forms.ComboBox EmailFormat;
        private System.Windows.Forms.Label FormatLabel;
    }
}
 


Ok so now to look at the code.

When we are working with sending emails, we need to use the System.Net.Mail namespace.  This used to be System.Web.Mail in earlier versions of the framework but Microsoft kindly moved it to keep us on our toes.  We will also be using a regular expression within our code as well as some File IO operations so we need namespaces for those as well.

So the first thing to do is add the following using statements:

using System.Text.RegularExpressions;
using System.Net.Mail;
using System.IO;


Now we can wire up an event handler for our Send button by clicking on it in design view and this will give us an empty event handler as follows: 

        private void Send_Click(object sender, EventArgs e)
        {
 
        }


We will need a boolean variable to keep track of whether our email is to be sent as HTML or Plain Text and we will also do some form validation.  If we encounter form validation problems then we will build up a list of error messages and for this we will use a StringBuilder so we can add these like this:

        private void Send_Click(object sender, EventArgs e)
        {
            StringBuilder errorMessage = new StringBuilder();
 
            bool isHTML = false;
        }


As  part of our form validation, we shall check that the format of email addresses entered into the To and From fields are ok.

To do this we will use a method which makes use of a regular expression.  This method will look like this:

        public static bool IsValidEmailFormat(string emailAddress)
        {
            if (string.IsNullOrEmpty(emailAddress))
            {
                return false;
            }
            else
            {
                string regExpression = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
 
                Regex reg = new Regex(regExpression);
 
                return reg.IsMatch(emailAddress);
            }
        }


Regular expressions are beyond the scope of this article so please accept that this works or and have a study of regular expressions for yourself if you need a holistic understanding of this.

Now back to our button click event handler.  The first bit of validation code will need to look like this:

            if (string.IsNullOrEmpty(To.Text))
            {
                errorMessage.AppendLine("Please enter a recipient");
            }
            else if (!IsValidEmailFormat(To.Text))
            {
                errorMessage.AppendLine("The recipient email is not a valid format");
            }


So what we are doing here is checking if a value has been entered into the To field and if not then adding a message line to our StringBuilder.  If an email address has been typed in then we also check if it is a valid email using the method we created earlier with the regular expression.  And so we will build up a list of all of our error messages and then either show these to the user in a MessageBox or if there are no error messages then we will send the email.

The rest of our validation code looks like this.

            if (string.IsNullOrEmpty(To.Text))

            {

                errorMessage.AppendLine("Please enter a recipient");

            }

            else if (!IsValidEmailFormat(To.Text))

            {

                errorMessage.AppendLine("The recipient email is not a valid format");

            }

 

            if (string.IsNullOrEmpty(From.Text))

            {

                errorMessage.AppendLine("Please enter a sender");

            }

            else if (!IsValidEmailFormat(From.Text))

            {

                errorMessage.AppendLine("The sender email is not a valid format");

            }

 

            if (string.IsNullOrEmpty(Subject.Text))

            {

                errorMessage.AppendLine("Please enter a subject");

            }

            if (string.IsNullOrEmpty(Body.Text))

            {

                errorMessage.AppendLine("Please enter a body for the message");

            }

            if (string.IsNullOrEmpty(Body.Text))

            {

                errorMessage.AppendLine("Please enter an SMTP Server");

            }

 

            if (!string.IsNullOrEmpty(AttachmentPath.Text))

            {

                if (!File.Exists(AttachmentPath.Text))

                {

                    errorMessage.AppendLine("The specified attachment does not exist");

                }

            }

 

            if (string.IsNullOrEmpty(EmailFormat.Text))

            {

                errorMessage.AppendLine("Please specify an email format");

            }

            else

            {

                isHTML = (EmailFormat.Text == "HTML");

            }

 

            if (UseAuthentication.Checked)

            {

                if (string.IsNullOrEmpty(Username.Text))

                {

                    errorMessage.AppendLine("Please enter an SMTP username");

                }

                if (string.IsNullOrEmpty(Password.Text))

                {

                    errorMessage.AppendLine("Please enter an SMTP password");

                }

            }

 

            if (errorMessage.Length > 0)

            {

                MessageBox.Show(errorMessage.ToString(), "Form Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }

            else if (!UseAuthentication.Checked)

            {

 

            }

            else

            {

 

            }


The last bit will then try and send the email with a block of code for if authentication is not ticked and a block of code for when it is ticked.

Before filling in the blanks in the above bit of code we will write our methods for sending emails.  Since we have different options for using authentication and not using authentication and sending an attachment or not sending an attachment, it seemd a reasonable idea to solve this problem by using method overloading.

So we will need method for the following sceanarios:

  • Send an unauthenticated email with no attachment
  • Send an unauthenticated email with an attachment
  • Send an authenticated email with no attachment
  • Send an authenticated email with an attachment

Our first method then will look like this:

        private void SendMail(string to, string from, string subject, string body, bool isHTML, string smtpServer)

        {

            MailMessage mailMessage = new MailMessage(from, to, subject, body);

 

            mailMessage.IsBodyHtml = isHTML;

 

            SmtpClient smtpClient = new SmtpClient(smtpServer);

 

            smtpClient.Send(mailMessage);

        }


So whats happening here is that first we create an instance of a MailMessage class and we call our variable which references this mailMessage.  The MailMessage class has a constructor which accepts 4 parameters which allows us to instantiate and populate the class instance all in one .

The MailMessage class determines if the mail is to be sent as plain text or html via a boolean property called IsBodyHtml.  We set this to be equal to our passed in parameter which ultimatley comes from what is selected in our drop down list for email format on our form.

We then create an instance of a SmtpClient class.  This has a constructor which allows you to pass in the email server we will be using.  This comes from our form and is a string.  It can be in the form of an IP adddess of a dns name eg 192.168.1.145 or myserver.mydomain.com.

We then finally call the send method of the SmtpClient object which takes our MailMessage object as a parameter and that's it we are done.

The next method overload for sending an unauthenticated email with an attachment is very simillar but with an extra parameter in the method signature and an extra line to add the attachment.  This method looks like this:

        private void SendMail(string to, string from, string subject, string body, bool isHTML, string smtpServer, string attachmentPath)

        {

            MailMessage mailMessage = new MailMessage(from, to, subject, body);

 

            mailMessage.Attachments.Add(new Attachment(attachmentPath));

 

            SmtpClient smtpClient = new SmtpClient(smtpServer);

 

            smtpClient.Send(mailMessage);

        }


The next overload is to send an authenticated email without an attachment so this is very simillar to our first method but with extra parameters for the username and password and a couple of extra lines to send authentication details to the server.  It's very simple code wise so should be self explanatory as follows:

        private void SendMail(string to, string from, string subject, string body, bool isHTML, string smtpServer, string username, string password)

        {

            MailMessage mailMessage = new MailMessage(from, to, subject, body);

 

            SmtpClient smtpClient = new SmtpClient(smtpServer);

 

            smtpClient.UseDefaultCredentials = false;

 

            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(username, password);

            smtpClient.Credentials = SMTPUserInfo;

 

            smtpClient.Send(mailMessage);

        }


 And finally the very last overload is to send an authenticated email with an attachment.  Nothing new to us here then and looking like this:

        private void SendMail(string to, string from, string subject, string body, bool isHTML, string smtpServer, string username, string password, string attachmentPath)

        {

            MailMessage mailMessage = new MailMessage(from, to, subject, body);

 

            SmtpClient smtpClient = new SmtpClient(smtpServer);

 

            mailMessage.Attachments.Add(new Attachment(attachmentPath));

 

            smtpClient.UseDefaultCredentials = false;

 

            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(username, password);

            smtpClient.Credentials = SMTPUserInfo;

 

            smtpClient.Send(mailMessage);

        }


Ok so now these method overloads are written we can and fill in the bit of code which calls these methods depending on what our form choices were.

            if (errorMessage.Length > 0)
            {
                MessageBox.Show(errorMessage.ToString(), "Form Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (!UseAuthentication.Checked)
            {
                try
                {
                    if (string.IsNullOrEmpty(AttachmentPath.Text))
                    {
                        SendMail(To.Text, From.Text, Subject.Text, Body.Text, isHTML, SMTPServer.Text);
                    }
                    else
                    {
                        SendMail(To.Text, From.Text, Subject.Text, Body.Text, isHTML, SMTPServer.Text, AttachmentPath.Text);
                    }
 
                    MessageBox.Show("The message has been sent", "Send Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There was a problem sending this email" + Environment.NewLine + Environment.NewLine + ex.Message);
                }
            }
            else
            {
                try
                {
                    if (string.IsNullOrEmpty(AttachmentPath.Text))
                    {
                        SendMail(To.Text, From.Text, Subject.Text, Body.Text, isHTML, SMTPServer.Text, Username.Text, Password.Text);
                    }
                    else
                    {
                        SendMail(To.Text, From.Text, Subject.Text, Body.Text, isHTML, SMTPServer.Text, Username.Text, Password.Text, AttachmentPath.Text);
                    }
 
                    MessageBox.Show("The message has been sent", "Send Results", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There was a problem sending this email" + Environment.NewLine + Environment.NewLine + ex.Message);
                }
            }


And for completeness here is the entire thing:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Text.RegularExpressions;

using System.Net.Mail;

using System.IO;

 

namespace EmailSender

{

    public partial class EmailForm : Form

    {

        public EmailForm()

        {

            InitializeComponent();

        }

 

        private void Send_Click(object sender, EventArgs e)

        {

            StringBuilder errorMessage = new StringBuilder();

 

            bool isHTML = false;

 

            if (string.IsNullOrEmpty(To.Text))

            {

                errorMessage.AppendLine("Please enter a recipient");

            }

            else if (!IsValidEmailFormat(To.Text))

            {

                errorMessage.AppendLine("The recipient email is not a valid format");

            }

 

            if (string.IsNullOrEmpty(From.Text))

            {

                errorMessage.AppendLine("Please enter a sender");

            }

            else if (!IsValidEmailFormat(From.Text))

            {

                errorMessage.AppendLine("The sender email is not a valid format");

            }

 

            if (string.IsNullOrEmpty(Subject.Text))

            {

                errorMessage.AppendLine("Please enter a subject");

            }

            if (string.IsNullOrEmpty(Body.Text))

            {

                errorMessage.AppendLine("Please enter a body for the message");

            }

            if (string.IsNullOrEmpty(Body.Text))

            {

                errorMessage.AppendLine("Please enter an SMTP Server");

            }

 

            if (!string.IsNullOrEmpty(AttachmentPath.Text))

            {

                if (!File.Exists(AttachmentPath.Text))

                {

                    errorMessage.AppendLine("The specified attachment does not exist");

                }

            }

 

            if (string.IsNullOrEmpty(EmailFormat.Text))

            {

                errorMessage.AppendLine("Please specify an email format");

            }

            else

            {

                isHTML = (EmailFormat.Text == "HTML");

            }

 

            if (UseAuthentication.Checked)

            {

                if (string.IsNullOrEmpty(Username.Text))

                {

                    errorMessage.AppendLine("Please enter an SMTP username");

                }

                if (string.IsNullOrEmpty(Password.Text))

                {

                    errorMessage.AppendLine("Please enter an SMTP password");

                }

            }

 

            if (errorMessage.Length > 0)

            {

                MessageBox.Show(errorMessage.ToString(), "Form Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }

            else if (!UseAuthentication.Checked)

            {

                try

                {

                    if (string.IsNullOrEmpty(AttachmentPath.Text))

                    {

                        SendMail(To.Text, From.Text, Subject.Text, Body.Text, isHTML, SMTPServer.Text);

                    }

                    else

                    {

                        SendMail(To.Text, From.Text, Subject.Text, Body.Text, isHTML, SMTPServer.Text, AttachmentPath.Text);

                    }

 

                    MessageBox.Show("The message has been sent", "Send Results", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

                catch (Exception ex)

                {

                    MessageBox.Show("There was a problem sending this email" + Environment.NewLine + Environment.NewLine + ex.Message);

                }

            }

            else

            {

                try

                {

                    if (string.IsNullOrEmpty(AttachmentPath.Text))

                    {

                        SendMail(To.Text, From.Text, Subject.Text, Body.Text, isHTML, SMTPServer.Text, Username.Text, Password.Text);

                    }

                    else

                    {

                        SendMail(To.Text, From.Text, Subject.Text, Body.Text, isHTML, SMTPServer.Text, Username.Text, Password.Text, AttachmentPath.Text);

                    }

 

                    MessageBox.Show("The message has been sent", "Send Results", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

                catch (Exception ex)

                {

                    MessageBox.Show("There was a problem sending this email" + Environment.NewLine + Environment.NewLine + ex.Message);

                }

            }

        }

 

        private void SendMail(string to, string from, string subject, string body, bool isHTML, string smtpServer)

        {

            MailMessage mailMessage = new MailMessage(from, to, subject, body);

 

            mailMessage.IsBodyHtml = isHTML;

 

            SmtpClient smtpClient = new SmtpClient(smtpServer);

 

            smtpClient.Send(mailMessage);

        }

 

        private void SendMail(string to, string from, string subject, string body, bool isHTML, string smtpServer, string attachmentPath)

        {

            MailMessage mailMessage = new MailMessage(from, to, subject, body);

 

            mailMessage.Attachments.Add(new Attachment(attachmentPath));

 

            SmtpClient smtpClient = new SmtpClient(smtpServer);

 

            smtpClient.Send(mailMessage);

        }

 

        private void SendMail(string to, string from, string subject, string body, bool isHTML, string smtpServer, string username, string password)

        {

            MailMessage mailMessage = new MailMessage(from, to, subject, body);

 

            SmtpClient smtpClient = new SmtpClient(smtpServer);

 

            smtpClient.UseDefaultCredentials = false;

 

            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(username, password);

            smtpClient.Credentials = SMTPUserInfo;

 

            smtpClient.Send(mailMessage);

        }

 

        private void SendMail(string to, string from, string subject, string body, bool isHTML, string smtpServer, string username, string password, string attachmentPath)

        {

            MailMessage mailMessage = new MailMessage(from, to, subject, body);

 

            SmtpClient smtpClient = new SmtpClient(smtpServer);

 

            mailMessage.Attachments.Add(new Attachment(attachmentPath));

 

            smtpClient.UseDefaultCredentials = false;

 

            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(username, password);

            smtpClient.Credentials = SMTPUserInfo;

 

            smtpClient.Send(mailMessage);

        }

 

        private void UseAuthentication_CheckedChanged(object sender, EventArgs e)

        {

            Username.Enabled = UseAuthentication.Checked;

            Password.Enabled = UseAuthentication.Checked;

        }

 

        public static bool IsValidEmailFormat(string emailAddress)

        {

            if (string.IsNullOrEmpty(emailAddress))

            {

                return false;

            }

            else

            {

                string regExpression = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

 

                Regex reg = new Regex(regExpression);

 

                return reg.IsMatch(emailAddress);

            }

        }

 

        private void AddAttachment_Click(object sender, EventArgs e)

        {

            OpenFileDialog openFileDialog = new OpenFileDialog();

 

            DialogResult result = openFileDialog.ShowDialog();

 

            if (result == DialogResult.OK)

            {

                AttachmentPath.Text = openFileDialog.FileName;

            }

        }

    }


Note also the methods for running when the use authentication checkbox is ticked and when the browse button is clicked to add an attachment.  The code here should be trivial and self explanatory.

Any comments are welcome.