【问题标题】:How can i send email weekly every user in asp.net core 2.2 i have done with asp.net mvc using global file [closed]我如何在asp.net core 2.2中每周向每个用户发送电子邮件,我已经使用全局文件使用asp.net mvc完成了[关闭]
【发布时间】:2019-08-22 14:18:46
【问题描述】:

我想发送我的所有注册用户每周新闻信,所以我需要在通过自动过程部署服务器后每周发送电子邮件,但我在 asp.net core 2.2 中找不到在我这样做之前我该怎么做在带有全局文件的 asp.net Mvc 中同样的事情,但我无法理解核心我该如何做到这一点,请给我一些有用的解决方案。 电子邮件代码工作查找

  public bool SendEmail(string email, string subjec, string body, string name)
    {
        try
        {
            string senderMail = "*****";
            string senderPass = "*****";
            string MailHostServer = "*******";
            string port = "587";
            string displayName = "Account Activation";

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(senderMail, displayName);

            mail.To.Add(email);
            mail.Subject = subjec;

            mail.IsBodyHtml = true;
            mail.Body = body;


            mail.Priority = MailPriority.Normal;

            var stmp = new SmtpClient();
            stmp.Credentials = new NetworkCredential(senderMail, senderPass);
            stmp.Host = MailHostServer;
            stmp.Port = Convert.ToInt32(port);
            stmp.EnableSsl = true;
            stmp.Send(mail);
            return true;
        }
        catch (Exception e)
        {

            return false;
        }


    }

【问题讨论】:

  • Windows 计划任务
  • 谢谢@stuartd,我已经完成了hangfire,它既简单又好用。
  • @HamzaShafiq 好消息 :)

标签: c# asp.net-core


【解决方案1】:

除了hangfire,你还可以使用Background tasks with hosted services in ASP.NET Core

如果您想在特定时间运行它,您可以使用:

public Task StartAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            var currentTime = DateTime.UtcNow;

            //run background task at Monday 11:00:00
            if (currentTime.DayOfWeek == DayOfWeek.Monday && currentTime.Hour == 11 && currentTime.Minute == 0 && currentTime.Second == 0)
            {
                _logger.LogInformation(currentTime.ToString());
                DoWork();
            }

        }
   }

在托管服务中使用 dbcontext:

How should I inject a DbContext instance into an IHostedService?

关于如何手动启动和停止它:

ASP.NET Core IHostedService manual start/stop/pause(?)

【讨论】:

  • 感谢您的帮助,但我已经使用 RecurringJob.AddOrUpdate(salesReport => salesReport.ForAllCustomers(), Cron.Weekly);
【解决方案2】:

如果你在windows机器上运行,你可以使用windows计划任务。

或者请查看此链接。

C# console app to send email at scheduled times

【讨论】:

    猜你喜欢
    • 2016-09-18
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2011-03-06
    • 2020-03-02
    • 2015-05-04
    相关资源
    最近更新 更多