Click here to Skip to main content
Click here to Skip to main content

An SMTP Email Component in C#

, 21 Apr 2008
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)

About the Author

Bertus Kruger
Web Developer
New Zealand New Zealand
No Biography provided

Comments and Discussions

 
QuestionThanks!! PinmemberAlex Houben8-May-14 2:56 
QuestionHiiiii PinmemberDeepika.Akula4-Jul-11 23:59 
GeneralAttachment file problem PinmemberBurak Akku2-Dec-09 4:08 
GeneralSMTP code Pinmemberken.tachyon20-Jun-09 15:26 
GeneralRe: SMTP code PinmemberMember 348574012-Jun-10 4:37 
GeneralIt works fine PinmemberMutu14-Jun-09 18:03 
GeneralButton Event Pinmembertoodie4-Mar-09 11:29 
GeneralRe: Button Event Pinmembertoodie5-Mar-09 4:32 
GeneralNull handle exception Pinmemberslewrate29-Sep-08 8:39 
GeneralSuper code example Pinmembersaariko21-Sep-08 22:08 
GeneralRe: Super code example PinmemberBertus Kruger22-Sep-08 18:55 
Generalpublic void SendCompleted(object sender, AsyncCompletedEventArgs e) PinmemberIAM...16-Sep-08 12:39 
GeneralConnecting to Gmail Pinmemberandrew10101016-Jul-08 2:24 
GeneralRe: Connecting to Gmail PinmemberBertus Kruger16-Jul-08 11:08 
Generalit help me a lot Pinmemberdaisy-yu24-May-08 5:02 
GeneralRe: it help me a lot PinmemberBertus Kruger16-Jul-08 11:10 
GeneralEasyMail with Attachments Pinmemberjltermarsch21-Apr-08 6:57 
GeneralRe: EasyMail with Attachments PinmemberBertus Kruger21-Apr-08 18:08 
GeneralRe: EasyMail with Attachments Pinmemberjltermarsch22-Apr-08 1:30 
QuestionEasyMail Pinmembersanjubaba243-Nov-09 16:30 
Questionmail component PinmemberGopalk124-Oct-07 20:49 
AnswerRe: mail component PinmemberBertus Kruger24-Oct-07 21:25 
GeneralNICE!! Pinmembertoodie25-Sep-07 4:54 
GeneralRe: NICE!! PinmemberBertus Kruger25-Sep-07 9:55 
QuestionProblem with the Email Component PinmemberSandeep0711198410-Aug-07 6:54 
AnswerRe: Problem with the Email Component [modified] PinmemberBertus Kruger28-Aug-07 11:19 
Generalun handlled execption has occur PinmemberPrabhakantha Chandrakumara20-Jul-07 5:27 
GeneralRe: un handlled execption has occur PinmemberBertus Kruger28-Aug-07 11:20 
Questioni cant log on Pinmemberselim akkoyunlu9-Jun-07 11:25 
AnswerRe: i cant log on PinmemberBertus Kruger9-Jun-07 20:27 
GeneralRe: i cant log on Pinmemberselim akkoyunlu9-Jun-07 23:45 
GeneralRe: i cant log on PinmemberBertus Kruger10-Jun-07 13:29 
GeneralRe: i cant log on Pinmemberselim akkoyunlu11-Jun-07 0:21 
GeneralRe: i cant log on PinmemberBertus Kruger11-Jun-07 9:17 
QuestionRe: i cant log on Pinmemberzein.Helal14-Apr-08 12:03 
Generalhelp to authentication Pinmemberselim akkoyunlu9-Jun-07 2:04 
GeneralPls Help Pinmemberwasif_Muhammad22-Feb-07 2:25 
GeneralRe: Pls Help PinmemberBertus Kruger22-Feb-07 9:39 
GeneralRe: Pls Help Pinmemberwasif_Muhammad22-Feb-07 18:01 
GeneralRe: Pls Help PinmemberBertus Kruger25-Feb-07 8:49 
Questionsmtp port number Pinmemberkonur34322-Dec-06 8:39 
AnswerRe: smtp port number PinmemberBertus Kruger22-Feb-07 9:42 
QuestionPolish Characters In Email Pinmemberali khan msc11-Oct-06 19:37 
QuestionQuestion by Cristiano Acosta PinmemberBertus Kruger27-Sep-06 10:49 
AnswerRe: Question PinmemberBertus Kruger27-Sep-06 10:52 
GeneralGood reference PinmemberAnytao21-Apr-06 3:59 
GeneralRe: Good reference PinmemberBertus Kruger7-May-06 13: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 | Mobile
Web04 | 2.8.140709.1 | Last Updated 22 Apr 2008
Article Copyright 2006 by Bertus Kruger
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid