从ASP.NET MVC Web应用发送每日通知邮件 [英] Send daily notification mail from asp.net mvc web app

查看:71
本文介绍了从ASP.NET MVC Web应用发送每日通知邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一个C#网络应用MVC,该API通过API调用从另一个站点(Trello)获取一些信息,并允许用户执行一些操作,例如打印带有所有卡详细信息的.xls文件.现在,我想实现一项功能,该功能每天在后台的特定时间每天发送一封邮件到带有该Excel附件的我的Gmail帐户.我想在一个外部项目中实现该功能,但是要在相同的解决方案中实现,但是我不知道该怎么做,我听说了quartz.net,但是我不知道它是如何工作的,我也不知道那是不是正确的解决方案.谁能帮助我,并给我一些提示?

p.s.我无法托管该应用

编辑-新问题


当我尝试使用Quartz.Net实现我的后台作业时,出现了我的类SendMailJob没有实现接口成员IJob.Execute的错误.

我该怎么办?

这是我的工作班级:

public class SendMailJob : IJob
{
    public void SendEmail(IJobExecutionContext context)
    {
        MailMessage Msg = new MailMessage();

        Msg.From = new MailAddress("mymail@mail.com", "Me");

        Msg.To.Add(new MailAddress("receivermail@mail.com", "ABC"));

        Msg.Subject = "Inviare Mail con C#";

        Msg.Body = "Mail Sended successfuly";
        Msg.IsBodyHtml = true;

        SmtpClient Smtp = new SmtpClient("smtp.live.com", 25);

        Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

        Smtp.UseDefaultCredentials = false;
        NetworkCredential Credential = new
        NetworkCredential("mymail@mail.com", "password");
        Smtp.Credentials = Credential;

        Smtp.EnableSsl = true;

        Smtp.Send(Msg);
    }
}

解决方案

如果您真的希望将它作为Asp.Net WebApp上的后台作业,则应进行以下研究:


Quartz.Net

创建作业以发送电子邮件

public class SendMailJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        ...Do your stuff;
    }
}

然后将您的作业配置为每天执行

// define the job and tie it to our SendMailJob class
IJobDetail job = JobBuilder.Create<SendMailJob>()
    .WithIdentity("job1", "group1")
    .Build();

// Trigger the job to run now, and then repeat every 24 hours
ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("trigger1", "group1")
    .StartNow()
    .WithSimpleSchedule(x => x
        .WithIntervalInHours(24)
        .RepeatForever())
    .Build();


HangFire

RecurringJob.AddOrUpdate(
    () => YourSendMailMethod("email@email.com"),
    Cron.Daily);


在您的startup.cs类中.在configure方法中添加它.

services.AddHostedService<SendMailHostedService>();


如果不需要将其作为后台作业托管在WebApp上,则可以创建Windows服务,该服务每天在需要的时间运行.

查看此问题: Windows服务调度每天每天凌晨6:00运行


要使用C#发送电子邮件,可以查看SmptClient

I've developed a C# web app MVC that gets some information from another site (Trello) through API calls, and allows the user to do some actions like printing an .xls file with all card details. Now, I want to implement a functionality that sends every day at a specific time in background a mail to my Gmail account with that Excel as an attachment. I want to implement that functionality in an external project but in the same solution, but I don't know how to do that, I heard about quartz.net but I didn't understand how it works and I don't know if that's the right solution. Can anyone help me and give me some tips?

p.s. I can't host the app

EDIT - New question


When I try to implement my background job with Quartz.Net I got this error that my class SendMailJob doesn't implement an interface member IJob.Execute.

What i have to do?

This is my jobs class:

public class SendMailJob : IJob
{
    public void SendEmail(IJobExecutionContext context)
    {
        MailMessage Msg = new MailMessage();

        Msg.From = new MailAddress("mymail@mail.com", "Me");

        Msg.To.Add(new MailAddress("receivermail@mail.com", "ABC"));

        Msg.Subject = "Inviare Mail con C#";

        Msg.Body = "Mail Sended successfuly";
        Msg.IsBodyHtml = true;

        SmtpClient Smtp = new SmtpClient("smtp.live.com", 25);

        Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

        Smtp.UseDefaultCredentials = false;
        NetworkCredential Credential = new
        NetworkCredential("mymail@mail.com", "password");
        Smtp.Credentials = Credential;

        Smtp.EnableSsl = true;

        Smtp.Send(Msg);
    }
}

解决方案

If you really want to it as background job on a Asp.Net WebApp you should look into:


Quartz.Net

Create a job to send e-mail

public class SendMailJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        ...Do your stuff;
    }
}

Then configure your job to execute daily

// define the job and tie it to our SendMailJob class
IJobDetail job = JobBuilder.Create<SendMailJob>()
    .WithIdentity("job1", "group1")
    .Build();

// Trigger the job to run now, and then repeat every 24 hours
ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("trigger1", "group1")
    .StartNow()
    .WithSimpleSchedule(x => x
        .WithIntervalInHours(24)
        .RepeatForever())
    .Build();


HangFire

RecurringJob.AddOrUpdate(
    () => YourSendMailMethod("email@email.com"),
    Cron.Daily);


IHostedService

public class SendMailHostedService : IHostedService, IDisposable
{
    private readonly ILogger<SendMailHostedService> _logger;
    private Timer _timer;

    public SendMailHostedService(ILogger<SendMailHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Hosted Service running.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, 
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        //...Your stuff here

        _logger.LogInformation(
            "Timed Hosted Service is working. Count: {Count}", executionCount);
    }

    public Task StopAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

In your startup.cs class. add this at configure method.

services.AddHostedService<SendMailHostedService>();


If do not need to host it as a backgroud job on your WebApp, then you can create a Windows Service that runs every day on the time you need.

See this question: Windows service scheduling to run daily once a day at 6:00 AM


To send E-mails with C# you can take a look a SmptClient class https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.send?view=netframework-4.8

Or use a service, like SendGrid, that can do it for you.

EDIT:


About your second question:

When you implements an interface your class should have all methods defined on that interface.

This methods needs to be public, return the same type, has the same name and receive the same parameters that was declared on the interface you implement.

In your specific case, you just miss the method name. Just change it do Execute like below.

EDIT: As you are using Quartz.net 3, the IJbo interface returns a Task and not void. So I changed the class SendMailJob to return a task of your existing method.

public class SendMailJob : IJob
{
    public Task Execute(IJobExecutionContext context)
    {
        return Task.Factory.StartNew(() => SendEmail());
    }

    public void SendMail()
    {
        MailMessage Msg = new MailMessage();

        Msg.From = new MailAddress("mymail@mail.com", "Me");

        Msg.To.Add(new MailAddress("receivermail@mail.com", "ABC"));

        Msg.Subject = "Inviare Mail con C#";

        Msg.Body = "Mail Sended successfuly";
        Msg.IsBodyHtml = true;

        SmtpClient Smtp = new SmtpClient("smtp.live.com", 25);

        Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

        Smtp.UseDefaultCredentials = false;
        NetworkCredential Credential = new
        NetworkCredential("mymail@mail.com", "password");
        Smtp.Credentials = Credential;

        Smtp.EnableSsl = true;

        Smtp.Send(Msg);
    }
}

这篇关于从ASP.NET MVC Web应用发送每日通知邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆