繁体   English   中英

如何在ASP.NET MVC-5 C#应用程序中使用Windows服务发送自动电子邮件

[英]How to send automatic email using windows service in asp.net mvc-5 c# app

我正在一个asp.net MVC-5 Web项目上工作,我必须每天向所有用户发送电子邮件。 我知道有两种方法可以做到这一点:

  1. Windows服务
  2. SQL Server代理作业。

我决定使用Windows服务 我正在使用Visual Studio 2013 for Web的Express版本,因此其中没有Windows服务模板。 大量研究之后,我在Visual Studio中创建了一个Windows服务作为控制台应用程序。 这是代码:

服务

public class FirstService : ServiceBase
{
        public FirstService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            this.EventLog.WriteEntry("FirstService Service Has Started");
        }

        protected override void OnStop()
        {
            this.EventLog.WriteEntry("FirstService Service Has Stopped");
        }

        private void InitializeComponent()
        {
            this.ServiceName = "FirstService";
            this.CanStop = true;
            this.AutoLog = false;
            this.EventLog.Log = "Application";
            this.EventLog.Source = "FirstService";
        }
}

安装程序

[RunInstaller(true)]
public class MyServiceInstaller : Installer
{
    private ServiceProcessInstaller FirstServiceProcessInstaller;

    private ServiceInstaller FirstServiceInstaller;

    public MyServiceInstaller()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        this.FirstServiceProcessInstaller = new ServiceProcessInstaller();
        this.FirstServiceProcessInstaller.Account = ServiceAccount.LocalSystem;
        this.FirstServiceProcessInstaller.Username = null;
        this.FirstServiceProcessInstaller.Password = null;
        this.FirstServiceInstaller = new ServiceInstaller();
        this.FirstServiceInstaller.Description = "FirstService Service Template";
        this.FirstServiceInstaller.DisplayName = "First Service";
        this.FirstServiceInstaller.ServiceName = "FirstService";
        this.FirstServiceInstaller.StartType = ServiceStartMode.Manual;
        this.Installers.AddRange(new Installer[] { this.FirstServiceProcessInstaller, this.FirstServiceInstaller });
    }
}

主要

static class Program
{
    [STAThread]
    static void Main()
    {
        ServiceBase.Run(new FirstService());
    }
}

此后,我已经使用installutil.exe成功安装了此服务,并且可以从“ 控制面板”->“管理工具”->“服务”成功启动和停止服务。 到目前为止,一切都很好。

现在,正如我前面提到的,我想在我的mvc-5应用程序中使用Windows服务向我的应用程序用户发送自动电子邮件,我有一些问题:

  1. 我如何将Windows Service集成到我的asp.net mvc-5应用程序中?
  2. 我如何将应用程序部署到服务器?
  3. 我将如何在应用程序托管服务器上安装Windows服务?

如果可能的话,请建议我任何包含示例的优秀教程。 谢谢!

我再提出两个选择:

  1. 创建一个控制台应用程序,并使用Task Scheduler在给定时间调用它。 这个选项非常简单。
  2. 使用Quartz.net 如果您使用共享主机环境,则此选项可能有效。

我不明白在Mvc应用程序中集成Windows服务的意思。

它们是两个不同的流程,因此您需要在流程之间实现任何形式的通信(例如,通过数据库,文件,消息传递等)。

  1. 您可以使用HTTPWebRequest / WebClient类调用控制器动作,该控制器动作会将邮件发送给用户。

2&3:您需要遵循与本地开发系统相同的步骤。

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM