我的世界会奔跑!

To strive, to seek, to find and not to yield, for the dream, with braveheart.
posts - 16, comments - 9, trackbacks - 0, articles - 4
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

.NET 2.0下发送邮件的方法

Posted on 2006-05-26 14:48 holly 阅读(542) 评论(3) 编辑 收藏

using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Reflection;
using System.Web;
using System.Web.Security;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Net;
using System.Net.Mail;

namespace  Business
{
    /// <summary>
    /// Summary description for SendMailLogic
    /// </summary>
    public class SendMailLogic
    {
        /// <summary>
        /// 单例访问成员变量
        /// </summary>
        private static readonly SendMailLogic instance = new SendMailLogic();

        /// <summary>
        /// 返回SendMailLogic的单个实例
        /// </summary>
        public static SendMailLogic Instance
        {
            get
            {
                return instance;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public SendMailLogic()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public SendMailResponse SendMail( SendMailRequest request )
        {
            try
            {
                MailMessage myMail = new MailMessage();
                myMail.From = new MailAddress( request.From );
                PaserMailAddress( request.To, myMail.To );
                PaserMailAddress( request.CC, myMail.CC );
                PaserMailAddress( request.Bcc, myMail.Bcc );
                myMail.Subject = request.Subject;
                myMail.Body = request.Body;

                if (request.Attachments != null)
                {
                    for (int i = 0; i < request.Attachments.Length; i++)
                    {
                        System.Net.Mail.Attachment mailAttach = new System.Net.Mail.Attachment(ByteArrayToStream(request.Attachments[i].FileData), request.Attachments[i].FileName);

                        myMail.Attachments.Add( mailAttach );
                    }
                }

                if (string.IsNullOrEmpty(ConfigurationManager.AppSettings[BizConsts.APPKEY_SMTP_SERVER]))
                {
                    throw new ApplicationException( "SMTP服务器未设置" );
                }

                //Smtp Server
                SmtpClient mailClient = new SmtpClient(ConfigurationManager.AppSettings[BizConsts.APPKEY_SMTP_SERVER]);

                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[BizConsts.APPKEY_SMTP_SERVERPORT]))
                {
                    //端口号
                    try
                    {
                        mailClient.Port = Int32.Parse(ConfigurationManager.AppSettings[BizConsts.APPKEY_SMTP_SERVERPORT]);
                    }
                    catch
                    {
                        throw new ApplicationException("SMTP服务器端口设置错误,端口必须设置为数值型");
                    }
                }

                if ( CheckMailUserConfig() )
                {
                    //需要指定帐户信息
                    mailClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings[BizConsts.APPKEY_MAIL_USER], ConfigurationManager.AppSettings[BizConsts.APPKEY_MAIL_USERPW]);

                    mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                }
              
                mailClient.Send(myMail);

                SendMailResponse response = new SendMailResponse();

                response.ErrorCode = BizConsts.ERRCODE_SUCCESSFUL.ToString();
                response.ErrorMsg = string.Empty;

                return response;
            }
            catch (SmtpFailedRecipientsException e)
            {
                Trace.Write("无法发送邮件到所有邮件地址:" + e.Message);

                SendMailResponse response = new SendMailResponse();

                response.ErrorCode = BizConsts.ERRCODE_FAILED.ToString();
                response.ErrorMsg = e.Message;

                return response;
            }
            catch (SmtpFailedRecipientException e)
            {
                Trace.Write("无法发送邮件到个别邮件地址:" + e.Message);

                SendMailResponse response = new SendMailResponse();

                response.ErrorCode = BizConsts.ERRCODE_FAILED.ToString();
                response.ErrorMsg = e.Message;

                return response;
            }
            catch (SmtpException e)
            {
                Trace.Write("发送邮件时的Smtp异常:" + e.Message);

                SendMailResponse response = new SendMailResponse();

                response.ErrorCode = BizConsts.ERRCODE_FAILED.ToString();
                response.ErrorMsg = e.Message;

                return response;
            }
            catch (Exception e)
            {
                Trace.Write("发送邮件时的异常:" + e.Message);

                throw new ApplicationException( "发送邮件时的异常" , e );
            }
        }

        /// <summary>
        /// 解析分解邮件地址
        /// </summary>
        /// <returns></returns>
        private void PaserMailAddress( string mailAddress, MailAddressCollection mailCollection  )
        {
            if (string.IsNullOrEmpty(mailAddress) )
            {
                return;
            }

            char[] separator = new char[2] {',',';' };
            string[] addressArray = mailAddress.Split(separator);

            foreach (string address in addressArray )
            {
                if(address.Trim() == "")
                {
                    continue;
                }

                mailCollection.Add(new MailAddress(address ));
            }
        }

        /// <summary>
        /// 检查是否配置了邮件帐户
        /// </summary>
        /// <returns></returns>
        private bool CheckMailUserConfig()
        {
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[BizConsts.APPKEY_MAIL_USER]))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 字节数组转换为流
        /// </summary>
        /// <param name="byteArray"></param>
        /// <returns></returns>
        private Stream ByteArrayToStream( byte[] byteArray )
        {
            MemoryStream mStream = new MemoryStream(byteArray);

            return mStream;
        }
    }

}

Feedback

#1楼  回复 引用   

2006-07-12 11:55 by ztzkin[未注册用户]
出现错误:服务器提交了协议冲突

#2楼  回复 引用   

2007-05-10 19:37 by kuery[未注册用户]
喜欢学习,也喜欢

#3楼  回复 引用   

2007-05-10 19:41 by senyline[未注册用户]

喜欢学习,喜难玩闹;喜欢沉静,也喜欢夜空……
希望我们能成为朋友

Email:palsenlin@hotmail.com