Share with together

独乐乐不如众乐乐

博客园 首页 新随笔 联系 订阅 管理

1、配置文件

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <!--1:是调试状态 0或者其他-->
    <add key="DebugStatus" value="1"/>
    <!--发送测试邮件接收地址 调试用-->
    <add key="DebugEmail" value="autumn@cnblogs.com"/>
    <!--是否写日志 0或者其他 否 1是 -->
    <add key="IsWriteServiceLog" value="1" />
    <!--是否写信息到日志 0或者其他 是 1否 -->
    <add key="IsWriteInfoLog" value="0" />
    <!--单位秒-->
    <add key="Mail_TimerInterval" value="120" />
  </appSettings>

  <system.net>
    <mailSettings>
      <smtp from="XXXX邮件通知中心<域用户名@域名.com>" >
        <network enableSsl="false" host="mail.域名.com" port="25" defaultCredentials="false" />
      </smtp>
    </mailSettings>
  </system.net>
  
</configuration>


 

 2、发送邮件类(MailSender)

public class MailCenter
    {
        #region 发送邮件
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">主题</param>
        /// <param name="emailBody">正文</param>
        /// <param name="mailTo">邮件地址列表,以分号隔开</param>
        public void SendMail(string subject, string emailBody, string mailTo)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                System.Net.Configuration.MailSettingsSectionGroup settings = System.Net.Configuration.NetSectionGroup.GetSectionGroup(config).MailSettings;
                System.Net.Configuration.SmtpSection smtpSection = System.Net.Configuration.NetSectionGroup.GetSectionGroup(config).MailSettings.Smtp;
                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(settings.Smtp.Network.Host, settings.Smtp.Network.Port);

                string[] address = mailTo.Split(new char[] { ';' });
                System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
                foreach (string item in address)
                {
                    mm.To.Add(item);
                }
                mm.From = new System.Net.Mail.MailAddress(smtpSection.From);
                mm.BodyEncoding = System.Text.Encoding.UTF8;
                mm.SubjectEncoding = System.Text.Encoding.UTF8;
                mm.IsBodyHtml = true;
                mm.Body = emailBody;
                mm.Subject = subject;

                sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                sc.Send(mm);
            }
            catch (Exception ex)
            {
                WriteTextLog("发送邮件失败", ex.InnerException.Message.ToString(), DateTime.Now);
            }
            finally
            {
            }
        }
        #endregion

        #region 写入日志到文本文件
        /// <summary>  
        /// 写入日志到文本文件  
        /// </summary>  
        /// <param name="action">动作</param>  
        /// <param name="strMessage">日志内容</param>  
        /// <param name="time">时间</param>  
        public static void WriteTextLog(string action, string strMessage, DateTime time)
        {
            string IsWriteServiceLog = ConfigurationManager.AppSettings["IsWriteServiceLog"];
            if (IsWriteServiceLog != "1")
                return;

            string path = AppDomain.CurrentDomain.BaseDirectory + @"\Log\";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            string fileFullPath = path + time.ToString("yyyy-MM-dd") + ".System.txt";
            StringBuilder str = new StringBuilder();
            str.Append("Time:    " + time.ToString() + "\r\n");
            str.Append("Action:  " + action + "\r\n");
            str.Append("Message: " + strMessage + "\r\n");
            str.Append("-----------------------------------------------------------\r\n\r\n");
            StreamWriter sw;
            if (!File.Exists(fileFullPath))
            {
                sw = File.CreateText(fileFullPath);
            }
            else
            {
                sw = File.AppendText(fileFullPath);
            }
            sw.WriteLine(str.ToString());
            sw.Close();
        }
        #endregion

    }

 3、测试代码

      #region 发送测试邮件
        /// <summary>
        /// 发送测试邮件
        /// </summary>
        public void SendTestEmail()
        {
            string debugEmail = "";
            if (ConfigurationManager.AppSettings.AllKeys.Contains("DebugEmail"))
            {
                debugEmail = ConfigurationManager.AppSettings["DebugEmail"].ToString();
            }

            if (string.IsNullOrEmpty(debugEmail))
            {
                //如果配置文件中没有配置该节点
                WriteTextLog("发送测试邮件失败!", "请检查配置项中[DebugEmail]是否配置", DateTime.Now);
                return;
            }

            MailCenter mc = new MailCenter();
            mc.SendMail("XXXX邮件通知中心发送的测试邮件" + DateTime.Now.ToString("yyyyMMddHHmmss"), "XXXX邮件通知中心发送的测试邮件:无正文", debugEmail);
        }

        #endregion

 

posted on 2016-08-01 16:27  寒枫  阅读(327)  评论(0编辑  收藏  举报