Click here to Skip to main content
11,481,850 members (65,240 online)
Click here to Skip to main content

An SMTP Email Component in C#

, 21 Apr 2008 CPOL 140.2K 472 58
Rate this:
Please Sign up or sign in to vote.
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.
  • 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.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.
  • 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 = "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:

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

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 = 
        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:

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)

Share

About the Author

Bertus Kruger
Web Developer
New Zealand New Zealand
No Biography provided

Comments and Discussions

 
QuestionThanks!! Pin
Alex Houben8-May-14 3:56
memberAlex Houben8-May-14 3:56 
QuestionHiiiii Pin
Deepika.Akula5-Jul-11 0:59
memberDeepika.Akula5-Jul-11 0:59 
GeneralAttachment file problem Pin
Burak Akku2-Dec-09 5:08
memberBurak Akku2-Dec-09 5:08 
GeneralSMTP code Pin
ken.tachyon20-Jun-09 16:26
memberken.tachyon20-Jun-09 16:26 
GeneralRe: SMTP code Pin
Member 348574012-Jun-10 5:37
memberMember 348574012-Jun-10 5:37 
GeneralIt works fine Pin
Mutu14-Jun-09 19:03
memberMutu14-Jun-09 19:03 
GeneralButton Event Pin
toodie4-Mar-09 12:29
membertoodie4-Mar-09 12:29 
GeneralRe: Button Event Pin
toodie5-Mar-09 5:32
membertoodie5-Mar-09 5:32 
GeneralNull handle exception Pin
slewrate29-Sep-08 9:39
memberslewrate29-Sep-08 9:39 
GeneralSuper code example Pin
saariko21-Sep-08 23:08
membersaariko21-Sep-08 23:08 
GeneralRe: Super code example Pin
Bertus Kruger22-Sep-08 19:55
memberBertus Kruger22-Sep-08 19:55 
Generalpublic void SendCompleted(object sender, AsyncCompletedEventArgs e) Pin
IAM...16-Sep-08 13:39
memberIAM...16-Sep-08 13:39 
GeneralConnecting to Gmail Pin
andrew10101016-Jul-08 3:24
memberandrew10101016-Jul-08 3:24 
GeneralRe: Connecting to Gmail Pin
Bertus Kruger16-Jul-08 12:08
memberBertus Kruger16-Jul-08 12:08 
Generalit help me a lot Pin
daisy-yu24-May-08 6:02
memberdaisy-yu24-May-08 6:02 
GeneralRe: it help me a lot Pin
Bertus Kruger16-Jul-08 12:10
memberBertus Kruger16-Jul-08 12:10 
GeneralEasyMail with Attachments Pin
jltermarsch21-Apr-08 7:57
memberjltermarsch21-Apr-08 7:57 
GeneralRe: EasyMail with Attachments Pin
Bertus Kruger21-Apr-08 19:08
memberBertus Kruger21-Apr-08 19:08 
GeneralRe: EasyMail with Attachments Pin
jltermarsch22-Apr-08 2:30
memberjltermarsch22-Apr-08 2:30 
QuestionEasyMail Pin
sanjubaba243-Nov-09 17:30
membersanjubaba243-Nov-09 17:30 
Questionmail component Pin
Gopalk124-Oct-07 21:49
memberGopalk124-Oct-07 21:49 
AnswerRe: mail component Pin
Bertus Kruger24-Oct-07 22:25
memberBertus Kruger24-Oct-07 22:25 
GeneralNICE!! Pin
toodie25-Sep-07 5:54
membertoodie25-Sep-07 5:54 
GeneralRe: NICE!! Pin
Bertus Kruger25-Sep-07 10:55
memberBertus Kruger25-Sep-07 10:55 
QuestionProblem with the Email Component Pin
Sandeep0711198410-Aug-07 7:54
memberSandeep0711198410-Aug-07 7:54 
AnswerRe: Problem with the Email Component [modified] Pin
Bertus Kruger28-Aug-07 12:19
memberBertus Kruger28-Aug-07 12:19 
Generalun handlled execption has occur Pin
Prabhakantha Chandrakumara20-Jul-07 6:27
memberPrabhakantha Chandrakumara20-Jul-07 6:27 
GeneralRe: un handlled execption has occur Pin
Bertus Kruger28-Aug-07 12:20
memberBertus Kruger28-Aug-07 12:20 
Questioni cant log on Pin
selim akkoyunlu9-Jun-07 12:25
memberselim akkoyunlu9-Jun-07 12:25 
AnswerRe: i cant log on Pin
Bertus Kruger9-Jun-07 21:27
memberBertus Kruger9-Jun-07 21:27 
GeneralRe: i cant log on Pin
selim akkoyunlu10-Jun-07 0:45
memberselim akkoyunlu10-Jun-07 0:45 
GeneralRe: i cant log on Pin
Bertus Kruger10-Jun-07 14:29
memberBertus Kruger10-Jun-07 14:29 
GeneralRe: i cant log on Pin
selim akkoyunlu11-Jun-07 1:21
memberselim akkoyunlu11-Jun-07 1:21 
GeneralRe: i cant log on Pin
Bertus Kruger11-Jun-07 10:17
memberBertus Kruger11-Jun-07 10:17 
QuestionRe: i cant log on Pin
zein.Helal14-Apr-08 13:03
memberzein.Helal14-Apr-08 13:03 
Generalhelp to authentication Pin
selim akkoyunlu9-Jun-07 3:04
memberselim akkoyunlu9-Jun-07 3:04 
GeneralPls Help Pin
wasif_Muhammad22-Feb-07 3:25
memberwasif_Muhammad22-Feb-07 3:25 
GeneralRe: Pls Help Pin
Bertus Kruger22-Feb-07 10:39
memberBertus Kruger22-Feb-07 10:39 
GeneralRe: Pls Help Pin
wasif_Muhammad22-Feb-07 19:01
memberwasif_Muhammad22-Feb-07 19:01 
GeneralRe: Pls Help Pin
Bertus Kruger25-Feb-07 9:49
memberBertus Kruger25-Feb-07 9:49 
Questionsmtp port number Pin
konur34322-Dec-06 9:39
memberkonur34322-Dec-06 9:39 
AnswerRe: smtp port number Pin
Bertus Kruger22-Feb-07 10:42
memberBertus Kruger22-Feb-07 10:42 
QuestionPolish Characters In Email Pin
ali khan msc11-Oct-06 20:37
memberali khan msc11-Oct-06 20:37 
QuestionQuestion by Cristiano Acosta Pin
Bertus Kruger27-Sep-06 11:49
memberBertus Kruger27-Sep-06 11:49 
AnswerRe: Question Pin
Bertus Kruger27-Sep-06 11:52
memberBertus Kruger27-Sep-06 11:52 
GeneralGood reference Pin
Anytao21-Apr-06 4:59
memberAnytao21-Apr-06 4:59 
GeneralRe: Good reference Pin
Bertus Kruger7-May-06 14:42
memberBertus Kruger7-May-06 14:42 

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

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

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