Use quartz. Net to send emails at regular intervals

Source: Internet
Author: User
Tags mailmessage smtpclient
About quartz. net

Quartz. NET is an open-source job scheduling framework on the. NET platform. It is first transplanted from quartz on the Java platform. The official website is http://quartznet.sourceforge.net/. the latest website is 1.0.3. It can be applied to winform programs and Asp.net programs. Job Scheduling can be understood as a scheduled task. For example, we punch in at every day within the working day and pay on the 10th of every month. For jobs that require automatic execution and no intervention, quartz. net is the best application environment. It can not only meet simple application scenarios similar to daily logging, but also implement the correspondence between complex jobs and triggers, because the regular expression is used to match the time interval to define the Job Scheduling time, the complex time interval scenario is also relatively simple.

Requirement Analysis

Sending emails to registered users at regular intervals based on the conditions is a frequently used function of website applications. In the case of big data, web applications are prone to browser death and server timeout response, in this case, Windows Services are more suitable. In combination with quartz. net, the program stability will be achieved.

Implementation

Here we use the Windows service to implement this application. First, create a project and add quartz. net reference. Note that a Windows service type project is created here. The primary file with the same name is servicesmain. CS, now in servicesmain. onstart and onstop in CS do not write code first. Right-click the view and add the service installation class. The system automatically creates the corresponding Installation File projectinstaller. CS. In this file, right-click and install the file class attributes to set some attributes.

Create the quartz. Net configuration file job. xml:

<?xml version="1.0" encoding="utf-8" ?>
<quartz xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" overwrite-existing-jobs="true">
<job>
<job-detail>
<name>SendMailJob</name>
<group>JobGroup</group>
<job-type>BatchSendMail.ServiceInvokeMain,BatchSendMail</job-type>
</job-detail>
<trigger>
<cron>
<name>SendMailJobTrigger</name>
<group>TriggerGroup</group>
<job-name>SendMailJob</job-name>
<job-group>JobGroup</job-group>
<start-time>2008-01-01T00:00:00</start-time>
<cron-expression>0/10 * * ? * *</cron-expression>
</cron>
</trigger>
</job>
</quartz>

For more information, see the official documentation. Note that the <Cron-expression> section is divided into six parts, seconds, minutes, hours, days, months, and years are represented in sequence. Wildcards can be used for representation. For example, * indicates any value ,? Indicates that no special value is specified. -Indicates a range. For example, 10-12 indicates the period from January 1, October to January 1, December in month. Here, we start to execute the service every 10 seconds every day.

Create an email sending class:

Public class sendmailclass {Public String fromaddr {Get; set;} Public String fromuser {Get; set;} Public String host {Get; set;} Public String loginuser {Get; set ;} public String password {Get; set;} Public String [] toaddr {Get; set;} Public String subject {Get; set;} Public String body {Get; set ;} public bool isbodyhtml {Get; set;} public sendmailclass () {} public sendmailclass (string fromaddr, string fromuser, string host, string loginuser, string password, string [] toaddress, string strsubject, string strbody, bool isbodyhtml) {fromaddr = fromaddr; fromuser = fromuser; host = host; loginuser = loginuser; Password = password; toaddr = toaddress; subject = strsubject; body = strbody; isbodyhtml = isbodyhtml;} // send the public static string send (sendmailclass mail) {smtpclient = new smtpclient (); mailmessage message = new mailmessage (); string result = ""; try {mailaddress fromaddress = new mailaddress (mail. fromaddr, mail. fromuser); smtpclient. host = Mail. host; smtpclient. port = 25; message. from = fromaddress; foreach (string ADDR in mail. toaddr) {message. to. add (ADDR);} message. isbodyhtml = Mail. isbodyhtml; message. body = Mail. body; smtpclient. send (Message); MessageBox. show ("sent successfully"); Result = "1";} catch (exception ex) {MessageBox. show (ex. message); Result = ex. message;} return result ;}}

You can save your email account to an XML file or write it to your code.

Code executed by the main program:

        public static void Start()        {            SendMailClass mail=new SendMailClass();            //....            SendMailClass.Send(mail);        }

Return to servicesmain. CS and add the onstart () method:

protected override void OnStart(string[] args){    ServiceBase[] ServicesToRun;    ServicesToRun = new ServiceBase[] { new ServiceMain() };    ServiceBase.Run(ServicesToRun);}

Then compile the project and generate the corresponding EXE file. to test whether the program is normal, install the server on your computer and test it. Create two batch files in the same directory as the EXE file to install and uninstall the service.

Install service. bat

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe  GoalBatchSendMail.exePAUSE

Uninstall service. bat

@echo offC:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe -u  GoalBatchSendMail.exePAUSE

Batch Processing of running the installation service

Open the computer service and see the newly installed Service:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.