Click here to Skip to main content
13,146,934 members (80,723 online)
Click here to Skip to main content
Add your own
alternative version


58 bookmarked
Posted 4 Apr 2006

An SMTP Email Component in C#

, 21 Apr 2008
Rate this:
Please Sign up or sign in to vote.
A simple e-mail component.


EasyMail is an easy mailing component to send e-mails using an SMTP client. All that you need to do is make sure that all of the SMTP settings are correctly configured.

This is only an example of how to send emails. To extend this component is very easy so I have left it up to the user to modify and improve it to your needs.

Building the Component DLL

  • Create a new "Windows Control Library".
  • In the Solution Explorer, delete UserControl1.cs.
  • Add a new item to the Control Library.
  • Create a new Component class with the name EasyMail.
  • Replace the newly created EasyMail class with the following code:
  • /// <summary>
    /// Easy mail component that only needs to be droped on
    /// your form to be used.
    /// </summary>
    public partial class EasyMail : Component
      // All the fields that are needed
      private string mMailFrom;
      private string mMailTo;
      private string mMailSubject;
      private string mMailBody;
      private string mSMTPServer;
      private int mSMTPPort;
      private string mSMTPUsername;
      private string mSMTPPassword;
      private bool mSMTPSSL;
      private MailMessage MailObject;
      // Properties
      public string MailFrom { set { mMailFrom = value; }
                               get { return mMailFrom; } }
      public string MailTo { set { mMailTo = value; }
                             get { return mMailTo; } }
      public string MailSubject
          { set { mMailSubject = value; }
            get { return mMailSubject; } }
      public string MailBody { set { mMailBody = value; }
                               get { return mMailBody; } }
      public string SMTPServer { set { mSMTPServer = value; }
                                 get { return mSMTPServer; } }
      public int SMTPPort { set { mSMTPPort = value; }
                            get { return mSMTPPort; } }
      public string SMTPUsername
          { set { mSMTPUsername = value; }
            get { return mSMTPUsername; } }
      public string SMTPPassword {
            set { mSMTPPassword = value; }
            get { return mSMTPPassword; } }
      public Boolean SMTPSSL { set { mSMTPSSL = value; }
                               get { return mSMTPSSL; } }
      // Functions
      public Boolean Send()
        // build the email message
        MailMessage Email = new MailMessage();
        MailAddress MailFrom = 
         new MailAddress(mMailFrom,mMailFrom);
        Email.From = MailFrom;
        Email.Subject = mMailSubject;
        Email.Body = mMailBody;
        // Smtp Client
        SmtpClient SmtpMail = 
        new SmtpClient(mSMTPServer,mSMTPPort);
        SmtpMail.Credentials = 
        new NetworkCredential(mSMTPUsername,mSMTPPassword);
        SmtpMail.EnableSsl = mSMTPSSL;
        Boolean bTemp = true;
         return true;
        catch (SmtpFailedRecipientsException ex)
         MessageBox.Show("The message was not sent!!!");
         bTemp = false;
        return bTemp;
      // Constructor
      public EasyMail()
        MailObject = new MailMessage();
        mMailFrom = "";
        mMailTo = "";
        mMailSubject = "";
        mMailBody = "";
        mSMTPServer = "";
        mSMTPPort = 25;
        mSMTPUsername = "";
        mSMTPPassword = "";
        mSMTPSSL = false;
      public EasyMail(IContainer container)
  • Make sure that all of the following "using" clauses are at the top of the file, and then build the component.
  • using System;
    using System.ComponentModel;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Text;
    using System.Net;
    using System.Net.Mail;
    using System.Windows.Forms;

Install the Email Component onto the Toolbox

  • Go to the Design view of a form.
  • Open the Toolbox.
  • Right click on the tab in the Toolbox where you want to add the Email control to (Components in this example).
  • Select "Choose items..." from the popup menu.
  • The "Choose Toolbox Items" window will open. Click on Browse, and select the email component's DLL file. Click OK to close the Choose Toolbox Item window. The new component will now be in the toolbox.

Using the Component

  • Select the EasyMail component and drop it onto your form. An EasyMail1 object will be created.
  • To use it, add the following code to a button event or wherever you want to run the send event from. (Replace the XXXs with the correct info.)
easyMail1.MailFrom = " XXX@XXX.XXX";
easyMail1.MailTo = " XXX@XXX.XXX";
easyMail1.MailSubject = "Subject";
easyMail1.MailBody = "Mail body";

easyMail1.SMTPServer = "";
easyMail1.SMTPUsername = "XXX";
easyMail1.SMTPPassword = "XXX";
if (easyMail1.Send())

Sending messages asynchronously or synchronously

Sending messages synchronously is not always desired. It could cause your user interface to freeze or hang. To solve this, we have a separate function in the SMTPClient class called sendasync. This allows messages to be sent in their own thread.

To add this capability, we need to add a new boolean property to enable/disable this option. We also need to add the code to execute the right function depending on the value of the new property.

New property:

private bool mSendAsync;
public bool SendAsync { set { mSendAsync = value; }
                        get { return mSendAsync; } }

Code that will react upon the new property. This will be added to the Send function.

string sTemp = "";
if (mSendAsync)

Better Exception Handling

Mail services may not always be available. So we will have to add a few exception handlers to catch unexpected events. To do this, I will test if a message was sent. If it was not sent, I will wait a few seconds before I try to resend it again.

I created two new properties: TryAgianOnFailure and TryAgainDelayTime.

private bool mTryAgianOnFailure;
private int mTryAgainDelayTime;

public bool TryAgianOnFailure 
  { set { mTryAgianOnFailure = value; }
    get { return mTryAgianOnFailure; } }
public int TryAgainDelayTime
  { set { mTryAgainDelayTime = value; }
    get { return mTryAgainDelayTime; }

Here is the code to make it work... this will be added to the Send function.

catch (SmtpFailedRecipientsException e)
    for (int k=0;k < e.InnerExceptions.Length;k++)
        bTemp = false;
        SmtpStatusCode StatusCode = 
        if (StatusCode==SmtpStatusCode.MailboxUnavailable||
                if (mTryAgianOnFailure)
                    // send the message
                    string sTemp = "";
                    if (mSendAsync)
                        SmtpMail.SendAsync(Email, sTemp);
                    // Message was sent.
                    bTemp = true;
            catch { bTemp = false}


This is only a simple example of how to make things easy in Visual Studio. I like components very much because everything is packaged together. If any thing should go wrong, you directly know where to find the problem. Creating controls is also a good way to improve your object orientation skills. I hope this has helped you in some way.

For more info, please go to my website...



I added a string[] property (MailAttachments) that will store a list of attachment file paths.


easyMail1.MailAttachments = new string[2];
easyMail1.MailAttachments[0] = "c:\\temp.txt";
easyMail1.MailAttachments[1] = "c:\\log.txt";


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Bertus Kruger
Web Developer
New Zealand New Zealand
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionThanks!! Pin
Alex Houben8-May-14 2:56
memberAlex Houben8-May-14 2:56 
QuestionHiiiii Pin
Deepika.Akula4-Jul-11 23:59
memberDeepika.Akula4-Jul-11 23:59 
GeneralAttachment file problem Pin
Burak Akku2-Dec-09 4:08
memberBurak Akku2-Dec-09 4:08 
GeneralSMTP code Pin
ken.tachyon20-Jun-09 15:26
memberken.tachyon20-Jun-09 15:26 
GeneralRe: SMTP code Pin
Member 348574012-Jun-10 4:37
memberMember 348574012-Jun-10 4:37 
GeneralIt works fine Pin
Mutu14-Jun-09 18:03
memberMutu14-Jun-09 18:03 
GeneralButton Event Pin
toodie4-Mar-09 11:29
membertoodie4-Mar-09 11:29 
GeneralRe: Button Event Pin
toodie5-Mar-09 4:32
membertoodie5-Mar-09 4:32 
GeneralNull handle exception Pin
slewrate29-Sep-08 8:39
memberslewrate29-Sep-08 8:39 
GeneralSuper code example Pin
saariko21-Sep-08 22:08
membersaariko21-Sep-08 22:08 
GeneralRe: Super code example Pin
Bertus Kruger22-Sep-08 18:55
memberBertus Kruger22-Sep-08 18:55 
Generalpublic void SendCompleted(object sender, AsyncCompletedEventArgs e) Pin
IAM...16-Sep-08 12:39
memberIAM...16-Sep-08 12:39 
GeneralConnecting to Gmail Pin
andrew10101016-Jul-08 2:24
memberandrew10101016-Jul-08 2:24 
GeneralRe: Connecting to Gmail Pin
Bertus Kruger16-Jul-08 11:08
memberBertus Kruger16-Jul-08 11:08 
Generalit help me a lot Pin
daisy-yu24-May-08 5:02
memberdaisy-yu24-May-08 5:02 
GeneralRe: it help me a lot Pin
Bertus Kruger16-Jul-08 11:10
memberBertus Kruger16-Jul-08 11:10 
GeneralEasyMail with Attachments Pin
jltermarsch21-Apr-08 6:57
memberjltermarsch21-Apr-08 6:57 
GeneralRe: EasyMail with Attachments Pin
Bertus Kruger21-Apr-08 18:08
memberBertus Kruger21-Apr-08 18:08 
GeneralRe: EasyMail with Attachments Pin
jltermarsch22-Apr-08 1:30
memberjltermarsch22-Apr-08 1:30 
QuestionEasyMail Pin
sanjubaba243-Nov-09 16:30
membersanjubaba243-Nov-09 16:30 
Questionmail component Pin
Gopalk124-Oct-07 20:49
memberGopalk124-Oct-07 20:49 
AnswerRe: mail component Pin
Bertus Kruger24-Oct-07 21:25
memberBertus Kruger24-Oct-07 21:25 
GeneralNICE!! Pin
toodie25-Sep-07 4:54
membertoodie25-Sep-07 4:54 
GeneralRe: NICE!! Pin
Bertus Kruger25-Sep-07 9:55
memberBertus Kruger25-Sep-07 9:55 
QuestionProblem with the Email Component Pin
Sandeep0711198410-Aug-07 6:54
memberSandeep0711198410-Aug-07 6:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170915.1 | Last Updated 22 Apr 2008
Article Copyright 2006 by Bertus Kruger
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid