Mobile Log In
       Building and Delivering
Quality Software Results


Send a Simple Email using a C#.NET Class Library

the Essence

This TechCrystal provides a simple Microsoft c# (OO) programming example, written for sending error diagnostic emails to the webmaster (or technical support mailbox).  From a software developer's perspective, the programming accomplishments are: 

  • instancing the SMTP client service
  • populating an email object
  • using the service to send the email

The routine shown exists within a namespace.  One way to create a C#.NET namespace class structure is to create a new C#.NET Windows Class Library project in Visual Studio 2015.


Visual Studio IDE Send Basic Email V3 Hard-coded C# Namespace

Why are we here?
  1. This example shows syntactical nuances and an example for instancing and populating a mail object, and sending an email using the .NET framework 4.5 and C#.NET


  2. A second example shows the properties we chose to soft-code so that the same version of the routine can be used in multiple websites


  3. The use of the independent project build approach (independent class library) shown with this example allows the email routine to be used by any code in the website project, even those within any language used within the APP_CODE directory area.

    1. If you are using more than one .NET language in the same website, such as mixing C#.NET, VB.NET and/or AVR.NET, then you know you must have a separate directory for each language within the APP_CODE directory (the most logical area to place for most shared routines).  Code within an APP_CODE directory cannot reference code within a separate APP_CODE directory in the same project due to the compilation hierarchy (with perhaps some lifting of restrictions when creating static routines).  There are no other restrictions regarding mixed language use for programming elsewhere in the project.
A Little More Background

Since we selected the namespace structure, we cannot code the namespace with any reference to HttpContext or web.config application keys.  However, the namespace structure allows us to invoke the routine from any code anywhere within a separate website project without any other restrictions (even if multiple .NET languages are being used).

Since we want to use the namespace within a website, we have to

  • compile the namespace into a .dll file

  • somehow indicate that the namespace .dll is essentially a pre-defined building block for the website

    1. such as by using drag and drop to copy the .dll file into the website's project Bin folder (which automatically creates a reference in the project and also creates an auto-update/refresh detection component)

In order to make the example easy to understand, we replaced various website based parameters with hard-coded literals.  The soft-coded version is Example 2.    


Example Code


Passing in parameters



MBody is passed by reference







Instancing the SmtpClient















Populating Various Properties of the Email Object



















using System;

 

namespace nsSendBasicEmailV3HardCoded

{

    public class clsSendBasicEmailV3HardCoded

    {

 

        //**********************************************

        // Self Contained, Simple Email Routine

        //**********************************************

        //   with defaults designed for sending website error

        //     diagnostic emails

 

        public void stcSendBasicEmailV3HardCoded(

            String MTo,

            String MFrom,

            String MReplyTo,

            String MSubject,

         ref System.Text.StringBuilder MBody)

        {

            // use the newer StringBuilder class to formulate the body text of the email

            //  (instead of a simple string object that would be destroyed and recreated

            //   with each change in value)

 

            // Declare and instance the service program that will send the message and

            //   interact with the SMTP server as a client

            System.Net.Mail.SmtpClient SMTPClientService = new System.Net.Mail.SmtpClient();

 

 

            // tell it the IP address of the SMTP server and

            //   the sender's (or an account holder's) email address and password

 

            SMTPClientService.Host = "mail.YOURMAILSERVERURL.com";

            // tell the SMTP service what port to use

            SMTPClientService.Port = Convert.ToInt32("1710");

            // set the credentials, which is basically an email account and it's password,

            // based on application keys (specified in web.config)

            SMTPClientService.Credentials = new System.Net.NetworkCredential(

                "Webmaster@YOURMAILSERVER.com",

                "YourPASSword1234");

 

            // the service program that will send the message and

            //   interact with the SMTP server as a client has already been declared and instanced and

            //   provided with a host name and credentials

 

 

            // Declare and instance the email object

            System.Net.Mail.MailMessage EmailMsgObj = new System.Net.Mail.MailMessage();

 

            EmailMsgObj.IsBodyHtml = true;

 

            // the .To and .ReplyTo properties became collections in .NET 2.0

            // the .ReplyToList property was added in .NET 4.0 and is now preferred over .ReplyTo

 

            // two initializing options, one is a simple string, the other is a mail address object

            if (MTo == "*default" || MTo == String.Empty)

                EmailMsgObj.To.Add("WebsiteSupportMgr@YOURMAILSERVER.com");

            else

                EmailMsgObj.To.Add(MTo);

 

            if (MFrom == "*default" || MFrom == String.Empty)

                MFrom = "Webmaster@YOURMAILSERVER.com";

            EmailMsgObj.From = new System.Net.Mail.MailAddress(MFrom);

 

            if (MReplyTo == "*default" || MReplyTo == String.Empty)

                EmailMsgObj.ReplyToList.Add("Webmaster@YOURMAILSERVER.com");

            else

                EmailMsgObj.ReplyToList.Add(MReplyTo);

 

            EmailMsgObj.Subject = MSubject;

            EmailMsgObj.Body = MBody.ToString();

 

            // SMTPClientService.Send is very stable and probably does not error out even if email not sent

            // thus no need to monitor for error condition

            //   (especiallly since this routine is used primarily to send diagnostic error emails to the webmaster)

            SMTPClientService.Send(EmailMsgObj);

 

 

        }

 

 

    }

 

 

}

 





Soft-Coding the Email Properties

Example 2


Example 2 shows where we chose to use soft-coding, such as use of clsFdnAnyCtxCS7.intSMTPServerPort" instead of "1710".  Thus, this routine is provided as an example of the soft-coding we considered appropriate, which is essentially tied to the applications settings level of the website (not explicitly shown).





        go to the home page Top of Tech Crystals     go to next series page Next in Tech Crystals     Site Map     Mobile View
You are at the web site of Tegratecs Development Corp.  Click here to go to the home page of this site...
Integrity, Integration and ROI from Your Software
Our contact information:
Tegratecs Development Corp.
1320 Tower Road
Schaumburg, IL 60173
847-397-0088
( please register or sign-in )
© 2017 Tegratecs Development Corp.