Jmail和微软自带的发邮件类库的使用

         我们在写程序的过程中,难免会遇到这样的问题,就是用户在您的网站下了订单,您要给用户发邮件通知,那么,如果你的程序是由C# 语言来完成的,那你打可以来看完这篇文章,如果不是的,那也不要浪费时间。

         首先,我们来言归正传,Jmail的使用,如果我们的开发计算机上没有注册Jmail的话,那我们要先注册一下Jmail,

         那么具体地注册的方法是什么呢?

         第一步,在网上下载一个Jmail.dll然后呢,放到C盘的一个文件夹下,                                 

                            具体注册方法,是先把Jmail.dll文件拷贝C盘的某一目录下(如C:\Jmail\Jmail.dll),然后执行命令Regsvr32 C:\Jmail\Jmail.dll即可

         第二步,很重要,如果你的计算机是64位的,那么,你注册之后,仍然报错,具体报什么错呢(示例):

             “检索 COM 类工厂中 CLSID 为 {E5FF9F62-0E7C-4372-8AD5-DA7D2418070C} 的组件时失败,原因是出现以下错误: 80040154”

              (这个说明你的Jmail仍然没有注册成功,虽然在dos下,可能提示已经注册成功了,但是,还有一个原因:

                         

必须记得,将解决方案编译为64位的,(改种方法主要解决,64位系统问题))

          那么Jmail在开发过程中的使用类,代码如下:

        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private SqlRunner sqlRunner = null;

        public PagaPropJob()
        {

            sqlRunner = new SqlRunner();
        }


        /// <summary>
        ///发送邮件 status:不发送-1 ;未发送0 ;发送成功1;发送失败2;邮箱地址不合法3
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="mailSubject"></param>
        /// <param name="mailBody"></param>
        /// <param name="filePath"></param>
        /// <param name="isUpdate"></param>
        public void SendEmailJob(DataTable dt, string mailSubject, string mailBody, string logoFilePath, string filePath, bool isUpdate)
        {
            string tableName = System.Configuration.ConfigurationSettings.AppSettings["tableName"].ToString();
            int success = 0;
            int error = 0;
            int errorMail = 0;
            string ids = "";
            string errorIds = "";
            string errorMailIds = "";
            IList<string> list = new List<string>();
            // list.Add("*****@dhlink.com");
            // list.Add("******@epass.net.cn");不用此邮箱
            //list.Add("********@epass.net.cn");
            // list.Add("*********@epass.net.cn");

            int listCount = list.Count;
            foreach (DataRow dr in dt.Rows)
            {
                MessageClass jmMessage = new MessageClass();
                jmMessage.Charset = "gb2312";
                jmMessage.ISOEncodeHeaders = false;
                jmMessage.From = "********@epass.net.cn";
                jmMessage.FromName = "****网";
                jmMessage.Subject = mailSubject;
                jmMessage.MailServerUserName = "*********@epass.net.cn";
                jmMessage.MailServerPassWord = "*********";
                // jmMessage.MailServerUserName = "***********@epass.net.cn";
                //  jmMessage.MailServerPassWord = "*********";
                //更换发送邮件的邮箱地址
                if (listCount > 0)
                {
                    int i = success % listCount;
                    jmMessage.From = list[i];
                    jmMessage.MailServerUserName = list[i];
                }

                //注释掉下面的行,否则附件会乱码
                //jmMessage.ContentType = "text/html";

                try
                {
                    //将email地址转换为小写后,验证邮件是否有效
                    if (IsEmail(dr["email"].ToString().Trim().ToLower()))
                    {
                        jmMessage.AddRecipient(dr["email"].ToString().Trim(), "", "");
                        //嵌入logo图片
                        if (!string.IsNullOrEmpty(logoFilePath))
                        {
                            string logoId = jmMessage.AddAttachment(logoFilePath, true, "logoPic");
                            mailBody = string.Format(mailBody, "cid:" + logoId);
                        }
                        jmMessage.HTMLBody = mailBody;

                        //附件
                        string[] fileArray = filePath.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                        List<string> fileList = new List<string>(fileArray);
                        foreach (string file in fileList)
                        {
                            jmMessage.AddAttachment(file, false, null);
                        }

                        if (dr["id"] != null && dr["id"].ToString().Length > 0)
                        {
                            string sql = "update " + tableName + " set fromEmail='" + jmMessage.From + "' where id = " + dr["id"].ToString();
                            sqlRunner.ExecuteSqlNonQuery(sql);
                        }

                        bool sendSuccess = jmMessage.Send("smtp.epass.net.cn", false);
                        if (sendSuccess)
                        {
                            success += 1;
                            ids += "," + dr["id"].ToString();
                            if (success % 20 == 0)
                            {
                                UpdateStatus(isUpdate, 1, ref ids);
                            }
                        }
                        else
                        {
                            error += 1;
                            errorIds += "," + dr["id"].ToString();
                            if (error % 20 == 0)
                            {
                                UpdateStatus(isUpdate, 2, ref errorIds);
                            }
                        }
                    }
                    else
                    {
                        errorMail += 1;
                        errorMailIds += "," + dr["id"].ToString();
                        if (errorMail % 20 == 0)
                        {
                            UpdateStatus(isUpdate, 3, ref errorMailIds);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.InnerException + "单个邮箱24小时发送邮件不能多于1000封。");
                }
                finally
                {
                    jmMessage = null;
                }

            }

            logger.Info("发送数量:" + success.ToString() + " ;失败数量:" + error.ToString());
            UpdateStatus(isUpdate, 1, ref ids);
            UpdateStatus(isUpdate, 2, ref errorIds);
            UpdateStatus(isUpdate, 3, ref errorMailIds);
        }
到此,我们的Jmail发送邮件的主方法已经了解完毕。

 

           下面我们讲解,.NET发送邮件的方法:

           首先,必须引用名称空间:

   

using System.Net.Mail;
using System.Net.Mime;
using System.Net;


           不多说了,直接上代码:

        public void SendMessage(DataTable dt, string title, string emailContent, string logoPicPath, string path, bool isUpdate)
        {
            string tableName = System.Configuration.ConfigurationSettings.AppSettings["tableName"].ToString();
            int success = 0;
            int error = 0;
            int errorMail = 0;
            string ids = "";
            string errorIds = "";
            string errorMailIds = "";
            string smtpServer = "mail.epass.net.cn";
            string fromEmail = "***@epass.net.cn";
            string password = "*****";
            string user = "***网";
            IList<string> list = new List<string>();

            // list.Add("*****@dhlink.com");
            // list.Add("*****@epass.net.cn");不用此邮箱
            //list.Add("*********@epass.net.cn");
            // list.Add("************@epass.net.cn");
            int listCount = list.Count;

            #region

            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    SmtpClient smtp = new SmtpClient(); //实例化一个SmtpClient 
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //将smtp的出站方式设为 Network 
                    smtp.EnableSsl = false;//smtp服务器是否启用SSL加密 
                    smtp.Host = smtpServer;//指定 smtp 服务器                    
                    smtp.Credentials = new NetworkCredential(fromEmail, password);
                    MailMessage message = new MailMessage(); //实例化一个邮件类 
                    message.Priority = MailPriority.High; //的优先级,分为 Low, Normal, High,通常用 Normal即可               
                    message.From = new MailAddress(fromEmail, user, System.Text.Encoding.UTF8);

                    // message.Bcc.Add(new MailAddress("tanxiaolu@epass.net.cn", "", Encoding.GetEncoding(936)));
                    message.Subject = title; //标题 
                    message.SubjectEncoding = System.Text.Encoding.UTF8;
                    message.IsBodyHtml = true; //正文是否是HTML格式mm.BodyEncoding = Encoding.GetEncoding(936); 
                    string mailContent = string.Format(emailContent, dr["bill_no"].ToString(), dr["order_no"].ToString());


                    #region 网页内容中插入图片

                    LinkedResource lrImage = null;
                    if (File.Exists(logoPicPath))
                    {
                        lrImage = new LinkedResource(logoPicPath, "image/jpeg");
                        lrImage.ContentId = "logoPic"; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ,如果设置不正确,不会显示图片
                    }
                    AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(mailContent, null, "text/html");
                    if (lrImage != null)
                    {
                        htmlBody.LinkedResources.Add(lrImage);
                    }
                    //将配置好的信息添加到邮件信息中
                    message.AlternateViews.Add(htmlBody);
                    message.Body = mailContent;

                    #endregion

                    //更换发送邮件的邮箱地址
                    if (listCount > 0)
                    {
                        int i = success % listCount;
                        message.From = new MailAddress(list[i], user, System.Text.Encoding.UTF8);
                    }
                    ContentType ct = new ContentType();
                    //附件
                    if (!string.IsNullOrEmpty(path))
                    {
                        string[] fileArray = path.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                        List<string> fileList = new List<string>(fileArray);

                        foreach (string file in fileList)
                        {
                            Attachment myA = new Attachment(path, ct.MediaType);
                            message.Attachments.Add(myA);
                        }
                    }

                    // string[] tos = dr["email"].ToString().Split(';');

                    if (proJob.IsEmail(dr["email"].ToString().Trim().ToLower()))
                    {
                        message.To.Add(new MailAddress(dr["email"].ToString().Trim().ToLower(), "", System.Text.Encoding.UTF8));

                    }
                    else
                    {
                        errorMail += 1;
                        errorMailIds += "," + dr["id"].ToString();
                        if (errorMail % 20 == 0)
                        {
                            proJob.UpdateStatus(isUpdate, 3, ref errorMailIds);
                        }
                    }

                    bool sendSuccess = true;
                    try
                    {
                        smtp.Send(message);
                    }
                    catch (Exception)
                    {
                        sendSuccess = false;
                    }


                    if (sendSuccess)
                    {
                        success += 1;
                        ids += "," + dr["id"].ToString();
                        if (success % 20 == 0)
                        {
                            string sql = "update " + tableName + " set fromEmail='" + fromEmail + "' where id in (" + ids.Substring(1) + ")";
                            sqlRunner.ExecuteSqlNonQuery(sql);
                            proJob.UpdateStatus(isUpdate, 1, ref ids);
                        }
                    }
                    else
                    {
                        error += 1;
                        errorIds += "," + dr["id"].ToString();
                        if (error % 20 == 0)
                        {
                            proJob.UpdateStatus(isUpdate, 2, ref errorIds);
                        }
                    }

                }
                catch
                {
                    error += 1;
                    errorIds += "," + dr["id"].ToString();
                    proJob.UpdateStatus(isUpdate, 2, ref errorIds);

                }
            }
            if (success > 0 && success <= 20)
            {
                proJob.UpdateStatus(isUpdate, 1, ref ids);
            }

            if (error >= 0 && error <= 20)
            {
                proJob.UpdateStatus(isUpdate, 2, ref errorIds);
            }
            logger.Info("发送数量:" + success.ToString() + " ;失败数量:" + error.ToString());
            #endregion
        }

那么,到底,BodyHtml=true这个,我们的内容该怎么编辑呢:

                            string mailSubject = "****通知";
                            StringBuilder sb = new StringBuilder();
                            sb.Append(@"<p>亲爱的用户:</p>");
                            sb.Append("<p style=' line-height:200%'>  您好!20**年*月**日我们给您发送了一封主题为“**通知”,由于我们的**失误,提供给您的订单号和运单号可能是错误的,在此,给您带来的不便,我们深表歉意。以下是我们更正的您的订单号和运单号,请以此为参考,再次感谢。");
                            sb.Append(" <br/>本次商品订单号为:");
                            sb.Append("{0}");
                            sb.Append(" <br/>本次商品运单号为:");
                            sb.Append("{1}");
                            sb.Append("<br/>      若您之前已经回复了我们的”亚马逊美国购物客户中文信息核对补充通知”邮件或已登录我们的信息采集页面,我们会按照正确的订单号进行后期统计,请放心。");
                            sb.Append("<br/>      您有任何疑问,请拨打我们的客服热线:****(工作日9:00-17:00),我们将竭诚为您服务。 ");
                            sb.Append("<br/></p> <p style='text_align:right;'>       <b>**网</b> ");
                            sb.Append("<br/>         " + DateTime.Now.ToString("yyyy-MM-dd"));
                            sb.Append("</p> ");

                            //英文对照


                            sb.Append(@"<br/><p>Dear customer,</p>");
                            sb.Append("<p style=' line-height:200%'>  We are very sorry for the possible wrong information about the order NO. and the tracking NO. in the E-Mail titled Notice for Amazon US customer checking and supplementing Chinese information that we sent to you on **** **, 20**.");
                            sb.Append("<br/>Please refer to the following correct order NO. and the tracking NO.:");
                            sb.Append("<br/>The order NO. is :");
                            sb.Append("{0}");
                            sb.Append("<br/>The tracking NO. is :");
                            sb.Append("{1}");
                            sb.Append("<br/>      If you have replied the above mentioned E-mail or you have logged onto our information collecting website, you can be assured that we will follow the correct order NO. to conduct the later process.");
                            sb.Append("<br/>      Sorry for any inconvenience and thanks for your kindly cooperation.For any question, please call our customer service hotline ****** (9:00am-5:00pm, working days). We will serve you with all sincerity.");
                            sb.Append("</p> <p style='text_align:right;'>       <b>****</b><br/> ");
                            sb.Append("      " + DateTime.Now.ToString("yyyy-MM-dd"));
                            sb.Append("</p style='text_align:right;'> ");


                            //添加签名
                            sb.Append(@"</br><span><div style='MARGIN: 10px; FONT-FAMILY: verdana; FONT-SIZE: 10pt'><div style='font-family: 宋体, Tahoma; font-size: 14px; line-height: normal;'><b>通关网客服中心</b>     <b>Service Center</b><br> <br> <img src='cid:logoPic' />");
                            sb.Append("<br>     <br>电话(T):***********     *****公司<br>客服热线(Service):******   Shanghai China-Easypass Information Technology CO.,LTD.<br>传真(F):**********              地址:上海市浦东新区********号   邮编(P.C.):201203<br>                                   ADD:NO.******** ROAD,PUDONG,SHANGHAI,CHINA<br> <br>-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br>Attention!<br>This electronic mail including attachments is intended only for the person(s) or entity to which it is addressed and may contain confidential and/or legally privileged material and information. Unauthorized disclosure, copying, distribution or use of this material and information may be unlawful and is strictly prohibited. If you are not the intended recipient and have received this mail in error, please immediately contact the sender and delete all contents of the e-mail as well as any copies made.<br>Thank You!<br>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- </div></div></span>");
                            string mailBody = sb.ToString();



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值