码迷,mamicode.com
首页 > Windows程序 > 详细

【C#】Windows服务守护并发送邮件通知

时间:2017-08-24 19:42:22      阅读:529      评论:0      收藏:0      [点我收藏+]

标签:发件人   pen   thread   .net   enables   from   配置   smtp   generic   

 

 

1. App.config 配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <appSettings>
    <!--发送的邮件地址-->
    <add key ="mailaddress" value="发送者的邮箱地址"/>
    <!--发送的邮件的密码-->
    <add key="mailpassword" value="发送者的邮箱密码"/>
    <!--邮件发送给谁-->
    <add key="mailto" value="通知接收人的邮箱"/>
    <!--发送邮件的内容-->
    <add key="mailcontent" value="windows 服务已停止,并已自动启动"/>
    <!--发送邮件的标题-->
    <add key="mailtitle" value="服务死掉提醒"/>
    <add key="sip" value="smtp.126.com"/>
  </appSettings>
</configuration>

  

 

2.主要代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.ServiceProcess;
using System.Configuration;
using System.Net.Mail;
using System.Net;

namespace Test
{
    class Program
    {
        private static object _lock = new object();
        //时间间隔
        private const int _trimerInterval = 20000;
        //监视服务名称
        private const string MyServiceName = "MongoDB";
        private static System.Timers.Timer _trimer = new Timer();
        static void Main(string[] args)
        {
            _trimer.Interval = _trimerInterval;
            _trimer.Enabled = true;
            _trimer.Elapsed += _trimer_Elapsed;
            Console.WriteLine("正在开启服务。。。。");
            Console.Read();
        }

        /// <summary>
        /// 事件间隔事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void _trimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //检测指定服务是否开启,如停止则发送邮件通知用户并自动开启
            if (!CheckService(MyServiceName))
            {
                //开启服务
                StartService(MyServiceName);
            }
        }

        /// <summary>
        /// 检测服务是否正常
        /// </summary>
        /// <param name="serviceName">检测的服务名称</param>
        /// <returns>返回 bool(true或false)</returns>
        private static bool CheckService(string serviceName)
        {
            bool result = true;
            try
            {
                lock (_lock)
                {
                    //获取本机所有的服务
                    ServiceController[] services = ServiceController.GetServices();
                    foreach (ServiceController service in services)
                    {
                        if (service.ServiceName.Trim() == serviceName.Trim())
                        {
                            //判断服务状态(Stopped:服务停止, StopPending:服务正在停止)     <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
                            if ((service.Status == ServiceControllerStatus.Stopped) || (service.Status == ServiceControllerStatus.StopPending))
                            {
                                result = false;
                                System.Threading.Thread.Sleep(10000);
                                //服务已停止,发送邮件给通知
                                 SendMail();
                                return result;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return result;
        }
        /// <summary>
        /// 开启指定服务
        /// </summary>
        /// <param name="serviceName">检测的服务名称</param>
        private static void StartService(string serviceName)
        {
            try
            {
                ServiceController[] services = ServiceController.GetServices();
                foreach (ServiceController service in services)
                {
                    if (service.ServiceName.Trim() == serviceName.Trim())
                    {
                        //开启服务
                        service.Start();
                        service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
                        Console.WriteLine("服务已成功开启");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }


        /// <summary>
        /// 发送邮件
        /// </summary>
        public static void SendMail()
        {
            //发送的邮箱地址
            var emailAcount = ConfigurationManager.AppSettings["mailaddress"];
            //发送的邮箱密码
            var emailPassword = ConfigurationManager.AppSettings["mailpassword"];
            //发送给谁
            var to = ConfigurationManager.AppSettings["mailto"];
            //发送内容
            var content = ConfigurationManager.AppSettings["mailcontent"];
            //邮件标题
            var mailtitle = ConfigurationManager.AppSettings["mailtitle"];
            //邮件服务器
            var mailservice = ConfigurationManager.AppSettings["sip"];
            //创建邮件发送实例
            MailMessage message = new MailMessage();
            //设置发件人,发件人需要与设置的邮件发送服务器的邮箱一致
            MailAddress fromAddr = new MailAddress(emailAcount);
            message.From = fromAddr;
            //设置收件人,可添加多个,添加方法与下面的一样
            message.To.Add(to);
            //设置邮件标题
            message.Subject = mailtitle;
            //设置邮件内容
            message.Body = content;
            //设置邮件发送服务器,服务器根据你使用的邮箱而不同,可以到相应的 邮箱管理后台查看,下面是QQ的
            SmtpClient client = new SmtpClient(mailservice, 25);
            //设置发送人的邮箱账号和密码
            client.Credentials = new NetworkCredential(emailAcount, emailPassword);
            //启用ssl,也就是安全发送
            client.EnableSsl = true;
            //发送邮件
            client.Send(message);
        }
    }
}

  

结果却出现了问题

技术分享

原来是没有获得管理员权限,可做如下操作

项目名称-->属性---安全性

技术分享

 

技术分享

 

 解决

技术分享

 

【C#】Windows服务守护并发送邮件通知

标签:发件人   pen   thread   .net   enables   from   配置   smtp   generic   

原文地址:http://www.cnblogs.com/qiuym/p/7424298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!