簡體   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