65.9K
CodeProject 正在变化。 阅读更多。
Home

电子邮件发送 Web 服务

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.90/5 (13投票s)

2008年11月6日

CPOL

2分钟阅读

viewsIcon

123778

downloadIcon

3662

不带附件的电子邮件发送 Web 服务。

引言

本文将向您展示创建电子邮件通知 Web 服务是多么简单。但不幸的是,我仍然无法在电子邮件中包含附件。如果您在服务客户端和服务使用者之间使用点对点连接,则添加附件非常容易。但是,如果您必须在两者之间包含服务注册表,那么实现起来将不会那么容易。

背景

我最近才开始我的 Web 服务开发和 WCF 开发。我发现电子邮件通知服务可以成为其他应用程序中可以重用的功能或模块之一。在找不到好的示例后,我决定自己动手做。顺便说一下,本文中电子邮件发送的详细功能和模块也来自 Code Project。我所做的是将此电子邮件发送模块从组件层暴露到服务层。对于了解 SOA(面向服务架构)的读者来说,他们会更好地理解我的意思。

创建一个新的 Web 服务

使用 VS 2008,您可以轻松地通过 VS2008 内部的模板创建 Web 服务。默认情况下,您应该获得一个“ASMX”文件和 C# 文件,它是“ASMX”文件的后台代码。

将您的组件作为服务暴露

如果您已经拥有自己的电子邮件通知模块,只需将其复制并粘贴到您的 Web 服务项目中即可。如果没有,您可以从我与本文一起上传的 zip 文件中获取它。

这种服务开发使您可以减少将现有组件更改为 Web 服务的精力,从而可以在其他应用程序或系统中重用它。即使它不是 SOA 的一个很好的例子,但它也可以被认为是 IT 环境中的 SOA 景观。

复制模块后,您可以开始创建一个接口,以将您的服务参数与模块参数链接起来。

通知服务代码

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);
        }
    }
}

示例通知模块代码

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;
        } 

历史

  • 2008 年 11 月 6 日:初始发布
© . All rights reserved.