Java to automate the background e-mail function

Source: Internet
Author: User
Tags email account server port

Web. xml file <?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD ">
<web-app>
<servlet>
<servlet-name>mailsenderservlet</servlet-name><!--Mail Sending program--
<servlet-class>com.email.MailSenderServlet</servlet-class>
<init-param>
<param-name>server</param-name><!--mail Server SMTP address--
<param-value>smtp.163.com</param-value>
</init-param>
<init-param>
<param-name>port</param-name><!--mail Server SMTP Port--
<param-value>25</param-value>
</init-param>
<init-param>
<param-name>address</param-name><!--Email Address--
<param-value>[email protected]</param-value>
</init-param>
<init-param>
<param-name>username</param-name><!--Email Account--
<param-value>username</param-value>
</init-param>
<init-param>
<param-name>password</param-name><!--Password--
<param-value>******</param-value>
</init-param>
<init-param>
<param-name>validate</param-name><!--Whether the SMTP server requires authentication--
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>time</param-name><!--Scan Database time interval (minutes)--
<param-value>5</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>servlet:package Com.email;import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;p ublic class Mailsenderservlet
Extends HttpServlet {
Private MailSender Sender;
Private Thread t; public void Init () throws Servletexception {
Sender = new MailSender ();
Sender.setroot (root);
String Server = getinitparameter ("server"); String port = getinitparameter ("port");
String address = Getinitparameter ("Address");
String username = getinitparameter ("username");
String Password = getinitparameter ("password");
if (server = = NULL | | port = = NULL | | address = NULL | | username = NULL | |
Password = = null) {
SYSTEM.OUT.PRINTLN ("System file Web. XML error: Mail Sender failed to initialize!") ");
Return
}
Sender.setserver (server);
Sender.setport (port);
Sender.setaddress (address);
Sender.setusername (username);
Sender.setpassword (password); String time = Getinitparameter ("Time");
if (time! = null) {
Sender.settime (Integer.parseint (time));
}
String validate = Getinitparameter ("Validate");
if (Validate! = null) {
Sender.setvalidate (boolean.valueof (Validate). Booleanvalue ());
}
t = new Thread (sender);
T.start (); Start the Mail send thread
} public void Destroy () {
Sender.stop (); Stop message sending thread
try {
T.join (1000);
if (t.isalive ()) {
System.out.println ("The Mail send thread does not stop.") ");
}
}
catch (Exception e) {}
}} Mail Sender package Com.email;import java.io.*;
Import java.sql.*;
Import java.util.*;
Import Java.util.Date;
Import javax.activation.*;
Import javax.mail.*;
Import javax.mail.message.*;
Import javax.mail.internet.*;/**
* <p>copyright:copyright (c) 2004</p>
* @author[email protected]
* @version 1.0
*/public class MailSender
Implements Runnable {private int time = 5 * 60 * 1000;//Scan database interval
Private Boolean flag = true; Stop thread tagging
Private String Server = "127.0.0.1"; SMTP server address
Private String port = "25"; SMTP Server port
Private String address; Sender's address for sending email
Private String username; Sender's user name
private String password; Sender's password
Private Boolean validate = true; Does the mail server require authentication
Private File root = null; Web root directory
Mailconfigmanager manager = Mailconfigmanager.getinstance (); Public MailSender () {
} public void Setaddress (String address) {
this.address = address;
} public void SetPassword (String password) {
This.password = password;
} public void Setport (String port) {
if (port! = null && port.length () > 0) {
This.port = port;
}
} public void Setserver (String server) {
This.server = server;
} public void Setusername (String username) {
This.username = Username;
} public void Setvalidate (Boolean validate) {
This.validate = Validate;
} public void settime (int minute) {
This.time = minute * 60 * 1000;
} public void Run () {
Long lasttime = new Date (). GetTime (); Save the time the previous message was sent
while (flag) {//server stops when the thread is retired
Long k = new Date (). GetTime ()-lasttime;
if (K <-1000) {//Prevent system modification time
Lasttime = new Date (). GetTime ();
Continue
}
if (k > time) {//over the set interval to start sending mail
SendData ();
Lasttime = new Date (). GetTime ();
}
try {
Thread.Sleep (100);
}
catch (Exception e) {}
}
} public void Stop () {
Flag = false;} /**
* Retrieve database and send mail
*/
private void SendData () {
ResultSet rs=null;//Reading database data

try {
Session session = Session.getinstance (GetProperties (), new Authentic ());
while (flag) {//server stops when the thread is retired
String toaddress = null;//send address (obtained from RS)
String subject = null;//message subject
String content = NULL;//message contents
String file[] = null;//All attachments (absolute path)

SendMail (Session, toaddress, subject, content, file);//Send mail
}
}
catch (Exception e) {
E.printstacktrace ();
}
finally {
if (rs!=null) {
try{
Rs.close ();
}
catch (SQLException e) {}
}
}
}  /**
* Send mail
* @param session
* @param toaddress Destination Address
* @param subject Mail subject
* @param content message contents (HTML)
* @param files Mail attachments
* @return is sent successfully
*/
Private Boolean SendMail (Session session, String toaddress, String subject,
String content, string[] files) {toaddress = "[email protected]"; try {
Message rs = new mimemessage (session); Address from = new internetaddress (address);
Rs.setfrom (from); Send Address
Rs.setrecipient (recipienttype.to, New InternetAddress (toaddress)); Receive address
Rs.setsubject (subject); Message subject
Multipart MP = new Mimemultipart ();
BodyPart html = new MimeBodyPart (); Html.setcontent (content, "text/html; CHARSET=GBK "); Message HTML content
Mp.addbodypart (HTML);
if (Files! = null && files.length > 0) {//Mail attachment
for (int i = 0; i < files.length; i++) {
MimeBodyPart MBP = new MimeBodyPart ();
Filedatasource FDS = new Filedatasource (files[i]);
Mbp.setdatahandler (New DataHandler (FDS));
Mbp.setfilename (Mimeutility.encodeword (Files[i]), "GBK", null));
Mp.addbodypart (MBP);
}
}
Rs.setcontent (MP); e-mail Full content
Rs.setsentdate (New Date ()); Send Time
Transport.send (RS); Send
return true;
}
catch (Exception e) {
E.printstacktrace ();
return false;
}
}  /**
* Mail Session Properties
* @return Session Properties
*/
Private Properties getProperties () {
Properties rs = new properties ();
Rs.put ("Mail.smtp.host", server);
Rs.put ("Mail.smtp.port", port);
Rs.put ("Mail.smtp.auth", validate?) "True": "false");
Return RS;
} public void Setroot (File root) {
This.root = root;
} class Authentic
Extends Authenticator {//Verify password public authentic () {
} public passwordauthentication getpasswordauthentication () {
return new passwordauthentication (username, password);
}  }}
This article is reproduced from the [Programming Assistant station]:http://www.91duoduo.com/jishu/java_xx.html?page=1&noid=ffhjbi&t=

Java to automate the background e-mail function

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.