创建自动发邮件的服务
一.创建服务
1.在VS中,菜单栏上,选择文件->新建->项目,选择“Windows 服务”,对项目重命名
2.在编辑菜单上,选择“查找和替换”将Service1改成ServiceEmail;
3.在Service1.cs[Design]中,将SeriviceNamede 名称属性设置为ServiceEmail;
4.将解决方案管理器中,将Service1.cs重命名为ServiceEmail.cs
二.向服务添加功能,将自定义事件日志功能添加到服务中
1.双击打开ServiceEmail.cs,从工具箱的组件将EventLog组件拖动到设计器中,查看代码
2.在ServiceEmail类中添加“事件日志”对象的声明,并添加或编辑构造函数定义自定义事件日志
public ServiceEmail()
{
InitializeComponent();
this.AutoLog = false;
if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
{
//不存在就创建新的
System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailSourceLog");
}
eventLog1.Source = "EmailSource";
eventLog1.Log = "EmailSourceLog";
}
3.定义服务启动时停止时发生的情况,找到创建项目时自动改写的OnStart方法与OnStop方法
4.修改其中的代码,添加定时和发送邮件的代码,具体如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Mail;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows;
namespace ServiceEmail
{
public partial class ServiceEmail : ServiceBase
{
public ServiceEmail()
{
InitializeComponent();
this.AutoLog = false;
if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
{
//不存在就创建新的
System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailSourceLog");
}
eventLog1.Source = "EmailSource";
eventLog1.Log = "EmailSourceLog";
}
System.Timers.Timer timer;//计时器
private static readonly string CurrentPath=AppDomain.CurrentDomain.BaseDirectory;
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer();
timer.Interval = 3000;//设置计时器事件间隔执行时间
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
eventLog1.WriteEntry("In OnStart");
//保存日志文件
string path = CurrentPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
FileStream filestream = new FileStream(path,FileMode.Append,FileAccess.Write);
StreamWriter sw = new StreamWriter(filestream);
sw.WriteLine("Start :"+DateTime.Now.ToShortDateString());
sw.Flush();
sw.Close();
filestream.Close();
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop");
}
public void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (e.SignalTime.Hour == 16)
{
SendText();
}
//if (e.SignalTime.Hour == 0 && e.SignalTime.Minute == 0 && e.SignalTime.Second == 0)
//{
// SendText();
//}
}
public void SendText()
{
try
{
SmtpClient MailClient = new SmtpClient("smtp-mail.outlook.com");
MailClient.EnableSsl = true;
//发送邮件的邮箱与密码
MailClient.Credentials = new System.Net.NetworkCredential("***@outlook.com", "***");
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("***@outlook.com");
Msg.To.Add(new MailAddress("***@outlook.com"));
Msg.Subject = "testSub";
Msg.Body = "testBody";
string userState = "test message1";
MailClient.SendAsync(Msg, userState);
}
catch (SmtpException ex)
{
string _err = ex.Message;
}
}
}
}
三.向服务添加安装程序
1.在解决方案资源管理器中,打开ServiceEmail.cs,选择查看设计器,选择添加安装程序,命名该组件为ProjectInstaller
2.在ProjectInstaller的设计界面中,选择serviceInstaller1的属性窗口,将ServiceName设置为ServiceEmail,在名称中将DisplayName设置为ServiceEmail
3.将StartType设置为AutoMatic
4.在设计器中,选择serviceProcessInstaller1,将Account属性设置为LocalSystem,这将使得本地服务账户上安装运行该服务
四.在解决方案资源管理器中,点击生成项目
五.安装服务
1. 在 Windows 7 和 Windows Server 中,打开“开始”菜单中“Visual Studio 工具”下的“开发人员命令提示”。 在 Windows 8 或 Windows 8.1 中,选择“开始”屏幕上的“Visual Studio 工具”图块,然后使用管理凭据运行开发人员命令提示。 (如果使用鼠标,右键单击“开发人员命令提示”,然后选择“以管理员身份运行”。)
2. 在命令提示窗口中,导航到包含项目输出的文件夹。 例如,在“我的文档”文件夹下,导航到 Visual Studio 2013\Projects\MyNewService\bin\Debug。
3. 输入以下命令:
installutil.exe ServiceEmail.exe
4.如果遇到错误'installutil.exe' is not recognized as an internal or external command,
operable program or batch file. 修改命令为“C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe ServiceEmail.exe”即可,其中“C:\Windows\Microsoft.NET\Framework64\v4.0.30319\”是对应于你电脑中installutil.exe的路径位置。
5.如果遇到错误“An exception occurred during the Install phase.
System.Security.SecurityException: The source was not found, but some or all eve
nt logs could not be searched. Inaccessible logs: Security.”是因为没有以管理员身份运行开发人员命令提示,需要右键单击“开发人员命令提示”,然后选择“以管理员身份运行”
六.启动与运行服务
1. 在 Windows 中,打开“开始”屏幕或“开始”菜单,然后输入 services.msc。
你应该会看见ServiceEmail列于“服务”窗口中。 服务窗口中的ServiceEmail
2. 在“服务”窗口中,打开你的服务的快捷菜,然后选择“启动”。
3. 打开该服务的快捷菜单,然后选择“停止”。
4. (可选)你可以在命令行中使用 net startServiceName 和 net stopServiceName 命令来启动和停止你的服务。
七.验证服务的事件日志输出
1. 在 Visual Studio 中,打开“服务器资源管理器”(键盘:Ctrl+Alt+S),然后访问本地计算机的“事件日志”节点。
2. 找到EmailSourceLog列表并将它展开。 你会看到你的服务执行的两个操作(启动和停止)的条目。
使用事件查看器查看事件日志条目。
有关服务的调试,可以去参阅下面的网址
http://msdn.microsoft.com/zh-cn/library/cktt23yw.aspx
http://msdn.microsoft.com/zh-cn/library/7a50syb3(v=vs.110).aspx