0

I want to send my all register user weekly news letter so i need to send email for every week after deploying server by automatic process but i can't find in asp.net core 2.2 how can i do this before i done this same thing in asp.net Mvc with global file but i can't understand in core how can i do this please give me some helpful solution. Email code working find

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


    }
stuartd
  • 70,509
  • 14
  • 132
  • 163
Hamza Shafiq
  • 69
  • 1
  • 13

2 Answers2

1

Besides hangfire, you could also use Background tasks with hosted services in ASP.NET Core

If you would like to run it at specific time, you could use:

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

        }
   }

For consuming dbcontext in hosted service:

How should I inject a DbContext instance into an IHostedService?

For how to start and stop it manually:

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

Ryan
  • 19,118
  • 10
  • 37
  • 53
  • thank you for your help but i have done with the hangfire using RecurringJob.AddOrUpdate( salesReport => salesReport.ForAllCustomers(), Cron.Weekly); – Hamza Shafiq Aug 23 '19 at 21:33
0

If you are run on windows machine, you can use Windows Scheduled Task.

Or please check this link.

C# console app to send email at scheduled times

arthur
  • 85
  • 7