Send daily notification mail from asp.net mvc web app [closed]

折月煮酒 提交于 2020-02-03 02:28:48

问题


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);
    }
}

回答1:


You can create a windows service or create a console application and schedule it in windows scheduler.I have implemented the Send-mail service using Windows services.




回答2:


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);
    }
}



回答3:


Use a library like Hangfire which lets you schedule background jobs and backs them with persistent storage.

You can then easily schedule a recurring job like:

RecurringJob.AddOrUpdate(
    () => SendEmail("user@domain"),
    Cron.Daily);

https://docs.hangfire.io/en/latest/tutorials/index.html - the first tutorial is about sending email



来源:https://stackoverflow.com/questions/59358040/send-daily-notification-mail-from-asp-net-mvc-web-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!