我已经开发了一个asp.net MVC Web应用程序,现在我想每天在后台发送一封电子邮件。我想将此功能添加到已经创建的外部项目中。在该项目中,我创建了此类,我需要一些帮助来完成这项工作。
public class SendMailJob : IJob
{
public Task 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);
//CONFIGURE 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();
}
}
我不了解Quartz.net的工作原理,我遇到的问题如下:
发送邮件的代码运行良好,我尝试过在索引视图中放置一个按钮,并在按下按钮时从控制器调用使用我编写的代码的操作。
答案 0 :(得分:2)
您需要采取的步骤:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;
using Quartz.Impl;
namespace ScheduledTask.Models
{
public class JobScheduler
{
public static void Start()
{
IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
scheduler.Start();
IJobDetail job = JobBuilder.Create<SendMailJob>().Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.withIntervalInHours(24)
.RepeatForever())
.Build();
scheduler.ScheduleJob(job, trigger);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;
using System.Net;
using System.Net.Mail;
namespace ScheduledTask.Models
{
public class Jobclass:IJob
{
public void Execute(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);
}
}
}
}
在global.asax.cs
的应用程序启动事件中
protected void Application_Start(Object sender, EventArgs e)
{
// keep whatever other code is there
JobScheduler.Start();
}