Recent projects when the customer put forward a demand: The system regularly send e-mail to its customers, to achieve the effect of notification. First to share the examples to everyone, if there is some help, please give us some applause!
First of all, the Java timer (java.util.Timer) has the function of scheduled execution of scheduled tasks, by setting the time interval of the timer, it will automatically perform pre-scheduled tasks after this interval (java.util. TimerTask)
such as: Every one hours to perform the task Timer.schedule (timertask, 0, 60 * 60 * 1000);
The first parameter of the schedule method is the task that needs to be performed, the type of this class is Java.util.TimerTask, the second parameter is the wait time before the task is executed, where 0 means no wait, and the third parameter is the interval, in milliseconds
Because we hope that when the Web project starts, the timer can automatically start the timing, so throughout the Web project life time, will be scheduled to perform tasks, so the class to start the timer can not be a general class, here with the Servlet listener class to start the timer, by configuring this listener in the configuration file, Allow it to load automatically at the start of the project and survive for the entire Web project life cycle.
To implement the Javax.servlet.ServletContextListener interface to use a servlet listener, the following is an example:
public class Mytimertask implements Servletcontextlistener
{
Private timer timer = null;
public void contextdestroyed (Servletcontextevent event)
{
Timer.cancel ();
Event.getservletcontext (). log ("timer destruction");
}
public void contextinitialized (Servletcontextevent event)
{
This is where the listener is initialized and the listener starts when Tomcat is started, where the timer function can be implemented
Timer = new timer (true);
Event.getservletcontext (). Log ("timer started");//add log to see in tomcat log
Calling exporthistorybean,0 indicates that the task has no delay, 5*1000 indicates that the task is performed every 5 seconds, 60*60*1000 represents one hours;
Timer.schedule (New SendEmail (Event.getservletcontext ()), 0,24*60*60*1000);
}
}
It takes two packages to send mail using JavaMail (I upload it below, download it): Activation.jar Mail.jar Send these two reports to the project's Lib directory
public class SendEmail extends TimerTask
{
Private ServletContext context = null;
Public SendEmail (ServletContext context)
{
This.context = context;
}
@Override
public void Run ()
{
/*
* e-mail sent below for JavaMail
*/
SYSTEM.OUT.PRINTLN ("Sending mail");
Properties Props=new properties ();
Props.put ("Mail.smtp.host", "smtp.163.com");//Sender uses e-mail email server I'm using a 163 server.
Props.put ("Mail.smtp.auth", "true"); So that you can pass the validation
Session s=session.getinstance (props);
S.setdebug (TRUE);
MimeMessage message=new MimeMessage (s);
Set sender/Recipient/subject/Time to Message object
InternetAddress from=new internetaddress ("[email protected]"); Send the mail from the origin (sender's mailbox), this is my e-mail address, use please change to your valid address
Message.setfrom (from);
InternetAddress to=new internetaddress (tto);//tto for Email destination (recipient mailbox)
message.setrecipient (message.recipienttype.to,to);
Message.setsubject (ttitle);// ttitle is the title of the message
message.setsentdate (New Date ());
bodypart mdp=new mimebodypart ();//Create a new BodyPart object that holds the contents of the message
mdp.setcontent (tcontent, "text/html;charset=utf-8");//set content and format for BodyPart objects/ Encoding method tcontent for message content
Multipart mm=new mimemultipart ();// Create a new Mimemultipart object to hold BodyPart to
//image (can actually hold more than one)
Mm.addbodypart (MDP);//Add BodyPart to the Mimemultipart object (you can join multiple BodyPart)
message.setcontent (mm);//use mm as the content of the message object
Message.savechanges ();
Transport transport=s.gettransport ("SMTP");
Transport.connect ("smtp.163.com", "Daida", "789-jik");//e-mail person account password, in addition to my account password, please modify when using.
Transport.sendmessage (Message,message.getallrecipients ());
Transport.close ();
}
}
catch (Exception e)
{
E.printstacktrace ();
}
}
}
}
The timer is configured in Web. Xml as:
<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.4"
Xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">
<listener>
<listener-class>cachay.saga.utils.MyTimerTask</listener-class>
</listener>
</web-app>
At this point, all operations have been completed and need to be added to Activation.jar Mail.jar
Java to implement mail timed delivery