Click here to Skip to main content
15,884,986 members
Articles / Web Development / ASP.NET

Email Sending Web Service

Rate me:
Please Sign up or sign in to vote.
2.90/5 (13 votes)
6 Nov 2008CPOL2 min read 122.5K   3.6K   73   10
Email Sending Web Service without attachment

Introduction

This article will show you how simple it is to create an Email Notification Web Service. But unfortunately I am still not able to include the attachment inside the email. It is quite easy to add an attachment if you are using point to point connection on your service client and service consumer. But if you have to include the Service Registry in between, then it will not be easy to achieve.

Background

I have started my web service development and WCF development recently. I found that the email notification service can be one of the functions or modules that can be reused on other applications. After failing to get some good examples, I decided to do it on my own. By the way the detail function and module of email sending in this article is also from Code Project. What I have done is just expose this email sending module from component layer to service layer. For those readers who know about SOA (Service Oriented Architecture), they will understand better what I am saying.

Create A New Web Service

With VS 2008, you can easily create a Web Service via the template inside the VS2008. By default, you should get an "ASMX" file and the C# file which is the background code for the "ASMX" file.

Expose your Component as Service

If you already have the email notification module on your own, just copy and paste into your web service project. If not, you can just get it from the zip file that I have uploaded together with this article.

This kind of service development enables you to reduce your effort to change your existing component to become a web service where later it can be reused in other applications or systems. Even though it is not a good example of SOA, but it can also be considered as SOA landscape in the IT landscape.

After copying the module, you can start creating an interface to link your service parameter with the module parameter.

Notification Service Code

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace EmailNotification
{
    /// <summary>
    /// Summary description for EmailNotification
    /// </summary>
    [WebService(Namespace = "http://MailServiceSample/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, 
    // using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class SentEmail : System.Web.Services.WebService
    {

        [WebMethod]
        public string Sending_Email(string strEmailAddrFrom, 
	string[] strEmailAddrTo, int intTotalEmailTo, string strAttachement)
        {
            EmailAlert NewMail = new EmailAlert();
            return NewMail.EmailSent(strEmailAddrFrom, 
		strEmailAddrTo, intTotalEmailTo, strAttachement);
        }
    }
}

Example Notification Module Code

C#
public string EmailSent(string strEmailAddrFrom, 
	string [] strEmailAddrTo, int intTotalEmailTo, string strAttachement)
        {
            string strSent= " ";
            try
            {
                // Initializes a new instance of the System.Net.Mail.MailMessage class. 
                myMailMessage = new MailMessage();

                // Obtains the e-mail address of the person 
                // the e-mail is being sent to. 

                for (int NumberOfEmails = 0; 
		NumberOfEmails < intTotalEmailTo; NumberOfEmails++)
                {
                    myMailMessage.To.Add(new MailAddress
				(strEmailAddrTo[NumberOfEmails]));
                }
              

                // Obtains the e-mail address of the person sending the message. 
                myMailMessage.From = new MailAddress(strEmailAddrFrom, "Admin");

                // You can add additional addresses by simply calling .Add again. 
                // Support not added in the current example UI. 
                // 
                // myMailMessage.To.Add( new System.Net.Mail.MailAddress
					( "addressOne@example.com" )); 
                // myMailMessage.To.Add( new System.Net.Mail.MailAddress
					( "addressTwo@example.com" )); 
                // myMailMessage.To.Add( new System.Net.Mail.MailAddress
					( "addressThree@example.com" )); 

                // You can also specify a friendly name to be displayed 
	       // within the e-mail 
                // application on the client-side for the To Address. 
                // Support not added in the current example UI. 
                // See the example below: 
                // 
                // myMailMessage.To.Add(new System.Net.Mail.MailAddress
	       // ( this.txtToAddress.Text, "My Name Here" )); 
                // myMailMessage.From(new System.Net.Mail.MailAddress
                // ( this.txtToAddress.Text, "Another Name Here" )); 

                // System.Net.Mail also supports Carbon Copy(CC) 
	       // and Blind Carbon Copy (BCC) 
                // Support not added in the current example UI. 
                // See the example below: 
                // 
                // myMailMessage.CC.Add ( new System.Net.Mail.MailAddress
	       //( "carbonCopy@example.com" )); 
                // myMailMessage.Bcc.Add( new System.Net.Mail.MailAddress
                // ( "blindCarbonCopy@example.com" )); 

                // Obtains the subject of the e-mail message 
                myMailMessage.Subject = "Error On Optimizer Program";

                // Obtains the body of the e-mail message. 
                myMailMessage.Body = "Error On Optimizer Program. 
			Please check the detail from the attachment";

                // Listed below are the two message formats that can be used: 
                // 1. Text 
                // 2. HTML 
                // 
                // The default format is Text.                     
                myMailMessage.IsBodyHtml = true;

                // Listed below are the three priority levels that can be used: 
                // 1. High 
                // 2. Normal 
                // 3. Low 
                // 
                // The default priority level is Normal. 
                // 
                // This section of code determines which priority level 
                // was checked by the user. 

                myMailMessage.Priority = MailPriority.High;

                //myMailMessage.Priority = MailPriority.Normal; 

                //myMailMessage.Priority = MailPriority.Low; 

                // Not Yet Implement
                // This section of code determines if the e-mail message is going to 
                // have an attachment. 
                if (strAttachement != "" || strAttachement != null)
                {
                    Attachment att = new Attachment(strAttachement);
                    myMailMessage.Attachments.Add(att);
                }
         
                // Custom headers can also be added to the MailMessage. 
                // These custom headers can be used to tag an e-mail message 
                // with information that can be useful in tracking an e-mail 
                // message. 
                // 
                // Support not added in the current example UI. 
                // See the example below: 
                // myMailMessage.Headers.Add( "Titan-Company", "Titan Company Name" );

                // Initializes a new instance of the System.Net.Mail.SmtpClient class. 
                SmtpClient myMailClient = new SmtpClient();

                // Obtains the email server name or IP address to use 
	       // when sending the e-mail. 
                myMailClient.Host = "Your Mail Host";

                // Defines the port number to use when connecting to the mail server. 
                // The default port number for SMTP is 25/TCP. 
                myMailClient.Port = 25;

                // Specifies the delivery method to use when sending the e-mail 
                // message. Listed below are the three delivery methods 
                // that can be used by namespace System.Net.Mail 
                // 
                // 1. Network = sent through the network to an SMTP server. 
                // 2. PickupDirectoryFromIis = 
	       // copied to the pickup directory used by a local IIS server. 
                // 3. SpecifiedPickupDirectory    = 
                // is copied to the directory specified by the 
                // SmtpClient.PickupDirectoryLocation property. 

                myMailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

                // Initializes a new instance of the System.Net.NetworkCredential class. 
                //NetworkCredential myMailCredential = new NetworkCredential(); 

                // Obtains the user account needed to authenticate to the mail server. 
                //myMailCredential.UserName = this.txtUserAccount.Text; 

                // Obtains the user password needed to authenticate to the mail server. 
                //myMailCredential.Password = this.txtUserPassword.Text; 

                // In this example we are providing credentials 
	       // to use to authenticate to 
                // the e-mail server. Your can also use the default credentials of the 
                // currently logged on user. 
                // For client applications, this is the desired 
                // behavior in most scenarios. In those cases the bool 
                // value would be set to true. 
                //myMailClient.UseDefaultCredentials = true; 

                // Obtains the credentials needed to authenticate the sender. 
                //myMailClient.Credentials = myMailCredential; 

                // Set the method that is called back when the send operation ends. 
                myMailClient.SendCompleted += new SendCompletedEventHandler
						(SendCompletedCallback);

                // Sends the message to the defined e-mail for processing 
                // and delivery with feedback. 
                // 
                // In the current example randomToken generation was not added. 
                // 
                //string randomToken = "randonTokenTestValue"; 
                //myMailClient.SendAsync( myMailMessage, randomToken );
                object userState = myMailMessage;
                try
                {
                    //you can also call myMailClient.SendAsync
                    // (myMailMessage, userState);
                    Console.WriteLine("Mail Sending In progress");
                    myMailClient.Send(myMailMessage);
                }
                catch (System.Net.Mail.SmtpException ex)
                {
                    Console.WriteLine(ex.Message, "Send Mail Error");
                    strSent = strSent + ex.Message;
                }
                myMailMessage.Dispose();
                strSent = "Mail Sent !!";
            }

            // Catches an exception that is thrown when the 
	   // SmtpClient is not able to complete a 
            // Send or SendAsync operation to a particular recipient. 
            catch (System.Net.Mail.SmtpException exSmtp)
            {
                Console.WriteLine("Exception occurred:" + 
			exSmtp.Message, "SMTP Exception Error");
                strSent = strSent + "Exception occurred:" + exSmtp.Message;
            }

            // Catches general exception not thrown using the 
	   // System.Net.Mail.SmtpException above. 
            // This general exception also will catch invalid formatted 
	   // e-mail addresses, because 
            // a regular expression has not been added to this example 
            // to catch this problem. 
            catch (System.Exception exGen)
            {
                Console.WriteLine("Exception occurred:" + 
			exGen.Message, "General Exception Error");
                strSent = strSent + "Exception occurred:" + exGen.Message;
            }
            return strSent;
        } 

History

  • 6th November, 2008: Initial post

License

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


Written By
Systems Engineer
Malaysia Malaysia
I am a Software Engineer base in a Manufacturing Company.

Comments and Discussions

 
Generalgood one Pin
vashk19-Apr-12 1:33
vashk19-Apr-12 1:33 
GeneralMy vote of 1 Pin
mheidari21-Oct-09 3:59
mheidari21-Oct-09 3:59 
Generalok article Pin
Donsw19-Jan-09 10:28
Donsw19-Jan-09 10:28 
QuestionRe-use?? Pin
Ramon Smits10-Nov-08 22:24
Ramon Smits10-Nov-08 22:24 
AnswerRe: Re-use?? Pin
Schelian HP11-Nov-08 3:27
Schelian HP11-Nov-08 3:27 
GeneralRe: Re-use?? Pin
Ramon Smits11-Nov-08 3:56
Ramon Smits11-Nov-08 3:56 
GeneralRe: Re-use?? Pin
Hani Beyrouthy2-Dec-08 3:00
Hani Beyrouthy2-Dec-08 3:00 
GeneralRe: Re-use?? Pin
Ramon Smits2-Dec-08 3:15
Ramon Smits2-Dec-08 3:15 
GeneralRe: Re-use?? Pin
Hani Beyrouthy2-Dec-08 4:37
Hani Beyrouthy2-Dec-08 4:37 
AnswerRe: Re-use?? Pin
titan402823-Dec-08 17:30
titan402823-Dec-08 17:30 
This services is create to allow more than 1 application use the same error notification services. This means the same function of email notification does not need to re develop in each application.

If you have better option to handle this please share with me..

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.