.Net Core Windows 服务:监听特定事件并发送邮件通知
以下是一个使用 .Net Core 实现的监听 Windows 事件的 Windows 服务,并在发现 EventID=133 的事件时立即发送邮件通知的示例代码:
-
创建一个新的 .Net Core 控制台应用程序,并在项目文件中添加 Microsoft.Windows.Compatibility NuGet 包。
-
在程序入口点 Main 方法中创建一个 Windows 服务,并调用 Start 方法启动它。在服务的 OnStart 方法中添加事件监视器:
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Win32;
namespace WindowsService
{
class Program
{
static async Task Main(string[] args)
{
var services = new ServiceCollection();
services.AddHostedService<WindowsService>();
var serviceProvider = services.BuildServiceProvider();
await serviceProvider.GetService<WindowsService>().RunAsync();
}
}
public class WindowsService : ServiceBase
{
private readonly EventLogWatcher _watcher;
private readonly EmailService _emailService;
public WindowsService()
{
_watcher = new EventLogWatcher('System', EventLogEntryType.Error, 133);
_emailService = new EmailService('smtp.gmail.com', 'user@gmail.com', 'password');
}
protected override void OnStart(string[] args)
{
_watcher.EventRecordWritten += OnEventRecordWritten;
_watcher.Enabled = true;
}
protected override void OnStop()
{
_watcher.Enabled = false;
}
private async void OnEventRecordWritten(object sender, EventRecordWrittenEventArgs e)
{
var emailSubject = $'Event {e.EventRecord.Id} occurred';
var emailBody = $'Event message: {e.EventRecord.FormatDescription()}';
await _emailService.SendEmailAsync('recipient@example.com', emailSubject, emailBody);
}
public async Task RunAsync()
{
await Task.Delay(-1);
}
}
public class EventLogWatcher
{
private readonly string _logName;
private readonly EventLogEntryType _entryType;
private readonly int _eventId;
private EventLogWatcher _watcher;
public EventLogWatcher(string logName, EventLogEntryType entryType, int eventId)
{
_logName = logName;
_entryType = entryType;
_eventId = eventId;
}
public event EventHandler<EventRecordWrittenEventArgs> EventRecordWritten;
public bool Enabled
{
get { return _watcher != null; }
set
{
if (value && _watcher == null)
{
_watcher = new EventLogWatcher(new EventLogQuery(_logName, PathType.LogName)
{
ReverseDirection = true,
Query = $'*[System/EventID={_eventId}]'
})
{
Enabled = true
};
_watcher.EventRecordWritten += OnEventRecordWritten;
}
else if (!value && _watcher != null)
{
_watcher.Enabled = false;
_watcher.EventRecordWritten -= OnEventRecordWritten;
_watcher.Dispose();
_watcher = null;
}
}
}
private void OnEventRecordWritten(object sender, EventRecordWrittenEventArgs e)
{
if (e.EventRecord.EntryType == _entryType)
{
EventRecordWritten?.Invoke(this, e);
}
}
}
public class EmailService
{
private readonly string _smtpServer;
private readonly string _username;
private readonly string _password;
public EmailService(string smtpServer, string username, string password)
{
_smtpServer = smtpServer;
_username = username;
_password = password;
}
public async Task SendEmailAsync(string recipient, string subject, string body)
{
using (var client = new SmtpClient(_smtpServer))
{
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(_username, _password);
client.EnableSsl = true;
await client.SendMailAsync(new MailMessage(_username, recipient, subject, body));
}
}
}
}
-
在 EmailService 类中添加一个 SendEmailAsync 方法,它将使用 SMTP 服务器发送电子邮件通知。在 OnEventRecordWritten 方法中调用此方法,并将事件记录信息作为电子邮件正文。
-
将服务安装到 Windows 服务管理器中,并使用服务管理器启动它。现在,当 Windows 事件日志中的 EventID 为 133 的错误事件被记录时,将会立即向指定的电子邮件地址发送通知邮件。
本文示例代码展示了如何使用 .Net Core 创建一个 Windows 服务,监听特定的 Windows 事件,并在事件发生时发送邮件通知。您可以根据实际需求调整代码逻辑,例如修改 EventID、邮件内容、接收地址等,实现更多功能。
注意:
- 本示例代码使用 Gmail 作为 SMTP 服务器,您需要修改
EmailService类中的相关配置信息,以使用您自己的 SMTP 服务器。 - 请确保您的 Windows 环境允许创建和运行自定义服务。
- 在部署服务之前,请仔细阅读相关安全配置信息,避免潜在的安全风险。
希望本文能够帮助您更好地理解 .Net Core Windows 服务的开发过程。如果您有任何问题或建议,欢迎留言讨论。
原文地址: https://www.cveoy.top/t/topic/n27x 著作权归作者所有。请勿转载和采集!