Click here to Skip to main content
Email Password   helpLost your password?

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

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

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

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralMy vote of 1
mheidari
4:59 21 Oct '09  
fun
Generalok article
Donsw
11:28 19 Jan '09  
ok article, next time use something everyone else might have and go more in depth. otherwise a good article.
GeneralRe-use??
Ramon Smits
23:24 10 Nov '08  
Why would you wrap an smtp service with a soap service? That really has nothing to do with SOA as you are suggesting.

Very bad example and I really hope that you aren't using this in a real application.
GeneralRe: Re-use??
Schelian HP
4:27 11 Nov '08  
Ramon Smits wrote:
Why would you wrap an SMTP service with a soap service

Ramon,
did you ever heard something about firewalls Smile , firewalls don't like SMTP protocol but they love HTTP ?
This could be the best reason to use a web service like this.
I use a web service like this since many many years.
I use it for sending error messages to my inbox from applications and windows services, which are installed on the networks of my customer.

regards
HP
GeneralRe: Re-use??
Ramon Smits
4:56 11 Nov '08  
Well.. SMTP is tcp/25 and applications should use the mailserver as closely as available to them because a remote server could be not reachable.

You are indeed correct that if you have an application in the wild and want to report errors and such then that is YOUR error report service. That service internally could fire a notification to your inbox. Having an error reporting component within your application sending a e-mail like notification with your e-mail like service doesn't make any sense.

The networks that do not allow outgoing tcp connections on port 25 probably also have ip whitelisting so there your application wouldn't even be able to reach your email like service. Then you even have a *better* possibility that the networks internal smtp server to be reachable.
GeneralRe: Re-use??
Hani Beyrouthy
4:00 2 Dec '08  
Consider this scenario as an advantage to wrapping .NET classes in a web service:
If you are developing a small application in a very simple language where you can't reference DLLs, call other programs or even open sockets but you can open web sites, then what to do?

Easy, wrap whatever functionality you are looking for inside a web service and then you can use it from almost anywhere.

Very good method if you're planning on using .NET in an environment where you have limited control.
GeneralRe: Re-use??
Ramon Smits
4:15 2 Dec '08  
I really don't understand you. Can you specify one or more languages?
GeneralRe: Re-use??
Hani Beyrouthy
5:37 2 Dec '08  
It's not a language per-se, it's more of an environment.

For example, we need this functionality in an IVR to automatically send a fax to the caller.
We can't use .NET or any other language that easily provides this functionality but we can open URLs.
So from the IVR, we can call the web service and specify the email recipient as a fax number, the subject and the body.
And on the server, we can use whatever we want (.NET) to transfer that mail into a fax and send it.

Another example would be to program the buttons on your IP-Phone to open a URL, that points to a .NET web service, and provide whatever functionality is needed.
There is no way to execute .NET code on the IP-Phone for example, so this method comes very handy.
GeneralRe: Re-use??
titan203
18:30 23 Dec '08  
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..


Last Updated 6 Nov 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010