Click here to Skip to main content
15,880,392 members
Articles / Programming Languages / C#

An SMTP Email Component in C#

Rate me:
Please Sign up or sign in to vote.
2.85/5 (18 votes)
21 Apr 2008CPOL3 min read 185K   865   59   47
A simple e-mail component.

Introduction

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.
  • Image 1

  • Create a new Component class with the name EasyMail.
  • Image 2

  • Replace the newly created EasyMail class with the following code:
  • C#
    /// <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.To.Add(mMailTo);
        
        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;
    
        try
        {
         SmtpMail.Send(Email);
         return true;
        }
        catch (SmtpFailedRecipientsException ex)
        {
         MessageBox.Show("The message was not sent!!!");
         bTemp = false;
        }
        return bTemp;
      }
           
      // Constructor
      public EasyMail()
      {
        InitializeComponent();
    
        MailObject = new MailMessage();
        mMailFrom = "";
        mMailTo = "";
        mMailSubject = "";
        mMailBody = "";
        mSMTPServer = "";
        mSMTPPort = 25;
        mSMTPUsername = "";
        mSMTPPassword = "";
        mSMTPSSL = false;
      }
    
      public EasyMail(IContainer container)
      {
        container.Add(this);
        InitializeComponent();
      }
    }
  • Make sure that all of the following "using" clauses are at the top of the file, and then build the component.
  • C#
    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.
  • Image 3

  • 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.
  • Image 4

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.)
C#
easyMail1.MailFrom = " XXX@XXX.XXX";
easyMail1.MailTo = " XXX@XXX.XXX";
easyMail1.MailSubject = "Subject";
easyMail1.MailBody = "Mail body";

easyMail1.SMTPServer = "smtp.mail.yahoo.com";
easyMail1.SMTPUsername = "XXX";
easyMail1.SMTPPassword = "XXX";
if (easyMail1.Send())
{
    MessageBox.Show("Sent...");
}

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:

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

C#
string sTemp = "";
if (mSendAsync)
    SmtpMail.SendAsync(Email,sTemp);
else
    SmtpMail.Send(Email);

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.

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

C#
catch (SmtpFailedRecipientsException e)
{
    for (int k=0;k < e.InnerExceptions.Length;k++)
    {
        bTemp = false;
    
        SmtpStatusCode StatusCode = 
        e.InnerExceptions[k].StatusCode;
        if (StatusCode==SmtpStatusCode.MailboxUnavailable||
        StatusCode==SmtpStatusCode.MailboxBusy)
        {
            try
            {
                if (mTryAgianOnFailure)
                {
                    Thread.Sleep(mTryAgainDelayTime);
                    // send the message
                    string sTemp = "";
                    if (mSendAsync)
                        SmtpMail.SendAsync(Email, sTemp);
                    else
                        SmtpMail.Send(Email);
                    // Message was sent.
                    bTemp = true;
                }
            }
            catch { bTemp = false}
        }
    }
}

Conclusion

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... www.ChatBert.com.

History

Update(2008/04/22)

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

Example:

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

License

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


Written By
Web Developer
New Zealand New Zealand
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

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