Monday, December 12, 2011

Send Email C# - Example Only


Summary
This example is a simple class that can be used to send email, written in C#

Description
This example shows everything needed to send an email except for the SMTP settings.  These settings will vary depending on who you are sending your email through.  While these settings can be hard coded, always place them in the web.config file or the app.config file.

Before We Begin
You'll need the SMTP settings in your web.config or app.config file.  Do a search for your email provider's SMTP settings.  Here is a skeleton to use:


<system.net>
    <mailSettings>
      <smtp>
        <network host="You email provider will tell you what to use (example. smtp.gmail.com)"
                 password="The password you use to log into your email account"
                 port="Your email provider will tell you what port to use"
           userName="youremailaddress@something.com"/>
      </smtp>
    </mailSettings>
  </system.net>

The clsSmtpClient Class




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;

namespace EmailDemo
{
    public class clsSmtpClient
    {
        private string _fromEmailAddress;
        private string _fromEmailName;
        private string _toEmailAddress;
        private string _messageSubject;
        private string _messageBody;
        private bool _complete = false;
        private string _error;
        SmtpClient mailClient = new SmtpClient();
        MailMessage message = new MailMessage();

        public string FromEmailAddress
        {
            get { return _fromEmailAddress; }
            set { _fromEmailAddress = value; }
        }

        public string FromEmailName
        {
            get { return _fromEmailName; }
            set { _fromEmailName = value; }
        }

        public string ToEmailAddress
        {
            get { return _toEmailAddress; }
            set { _toEmailAddress = value; }
        }

        public string MessageSubject
        {
            get { return _messageSubject; }
            set { _messageSubject = value; }
        }

        public string MessageBody
        {
            get { return _messageBody; }
            set { _messageBody = value; }
        }

        public string Error
        {
            get { return _error; }
            set { _error = value; }
        }

        public bool Complete
        {
            get { return _complete; }
            set { _complete = value; }
        }


        /*
         * Constructor
         */
        public clsSmtpClient(string fromEmailAddress,
                             string fromEmailName,
                             string toEmailAddress,
                             string messageSubject,
                             string messageBody)
        {
            FromEmailAddress = fromEmailAddress;
            FromEmailName = fromEmailName;
            ToEmailAddress = toEmailAddress;
            MessageSubject = messageSubject;
            MessageBody = messageBody;

            setupClient();
        }

        /*
         * Default Constructor
         */
        public clsSmtpClient(string fromEmailAddress, string fromEmailName)
        {
            mailClient.EnableSsl = true;
            FromEmailAddress = fromEmailAddress;

            FromEmailName = fromEmailName;

            MailAddress fromAddress = new MailAddress(FromEmailAddress, FromEmailName);
        }


        private void setupClient()
        {
            // Smtp Client - other settings in web.config for safeness
            mailClient.EnableSsl = true;

            // To and From address objects
            MailAddress fromAddress = new MailAddress(FromEmailAddress, FromEmailName);
            MailAddress toAddress = new MailAddress(ToEmailAddress);

            // Build the message
            message.From = fromAddress;
            message.To.Add(toAddress);
            message.Subject = MessageSubject;
            message.Body = MessageBody;
        }


        public void setToAddress(string str)
        {
            MailAddress toAddress = new MailAddress(str);
            message.To.Clear();
            message.To.Add(toAddress);
        }

        public void setMessageBody(string str)
        {
            message.Body = str;
        }

        public void SendEmail()
        {
            try
            {
                mailClient.Send(message);
                Complete = true;
                Error = "Complete!";
            }
            catch (Exception mailException)
            {
                Complete = false;
                Error = mailException.Message.ToString();
            }
        }

    }
}

How do we use it?
Below is an example of how to use this class to make emailing simple.

             // In a winform project, remove "Server.HtmlEncode"
           
             // This is the email address you want to send to, taken from a textbox control.

            string toEmail = Server.HtmlEncode(txtMessageTo.Text);
             // This is the email subject taken from a textbox control
            string messageSubject = Server.HtmlEncode(txtMessageSubject.Text);
             // This is the actual message of the email taken from a textbox control
            string messageBody = Server.HtmlEncode(txtMessageBody.Text);
         
            /*
             * Logic tier - clsSmtpClient
             *      Mail logic is put in another class
             *      and implemented here concisely.
            */

            // Smtp Client - other settings in web.config for safeness.
            clsSmtpClient mySmtpClient = new clsSmtpClient("the email address you are sending from",
                                                           "the from email name you want to use",
                                                           toEmail,
                                                           messageSubject,
                                                           messageBody);

                // Send the email.
                mySmtpClient.SendEmail();
             
                // After sending an email, we have two outcomes... it either sent or failed.
                // Below, we check for both.
                // check to see if the email got sent.
                if (mySmtpClient.Complete)
                {

                    // If the email was sent without problems,
                    // do the following..  yours will be different
                    // Everything below is just a summary of what was sent.

                    pnlInput.Visible = false;
                    pnlResult.Visible = true;

                    lblEmailToReturn.Text = toEmail;
                    lblMessageSubjectReturn.Text = messageSubject;
                    lblMessageBodyReturn.Text = messageBody;
                }
             
                // If the email failed to send for some reason, no internet connection, etc.
                else if (!mySmtpClient.Complete)
                {
                    // This code gets the error message and sets a label with it.
                    lblError.Text = mySmtpClient.Error;
                    pnlInput.Visible = false;
                    pnlResult.Visible = false;
                    pnlError.Visible = true;
             
                }
        }







No comments:

Post a Comment