1、SendEmail类(邮件发送的核心类):
package com.jmwyw.tools;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.search.SentDateTerm;
public class SendEmail {
static String smtpHost = "smtp.126.com";
static String UserEmail = "gzswly@126.com" ;
static String UserPassword ="gzswly123";
static String Nickname ="贵州省物流云平台";
/**
*
* @param toEmail
* 接收人邮箱地址
* @param subject
* 主题(标题)
* @param messageText
* 内容
* @throws MessagingException
*/
@SuppressWarnings("static-access")
public static boolean sendMessage( String toEmail, String subject, String messageText) throws MessagingException {
// 第一步:配置javax.mail.Session对象
try {
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.starttls.enable", "true");// 使用 STARTTLS安全连接
// props.put("mail.smtp.port", "25"); //google使用465或587端口
props.put("mail.smtp.auth", "true"); // 使用验证
// props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props, new MyAuthenticator(UserEmail, UserPassword));
// 第二步:编写消息
InternetAddress fromAddress = new InternetAddress(UserEmail, Nickname);
InternetAddress toAddress = new InternetAddress(toEmail);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(fromAddress);
message.addRecipient(RecipientType.TO, toAddress);
message.setSentDate(Calendar.getInstance().getTime());
message.setSubject(subject);
message.setContent(messageText, "text/html;charset=utf-8");
// 第三步:发送消息
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost, UserEmail, UserPassword);
transport.send(message, message.getRecipients(RecipientType.TO));
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/*public static void main(String[] args) {
try {
sendMessage("maz@xdot.com.cn", "ddddd", "<div style='width:300px;height:200px;text-align:center;'><span style='color:red;float:red'>safasssssdfas</span></div>");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}
class MyAuthenticator extends Authenticator {
String userName = "";
String password = "";
public MyAuthenticator() {
}
public MyAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
2、SentEmail类(通过线程来跑SendEmail):
package com.jmwyw.timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jmwyw.tools.SendEmail;
public class SentEmail extends TimerTask {
private static final Logger log = Logger.getLogger(SentEmail.class);
private static java.text.SimpleDateFormat dtf = new java.text.SimpleDateFormat(
"yyyy-MM-dd");
/*
* 被调用具体的方法
*/
public void run() {
long tick = System.currentTimeMillis();
try {//处理用户信息
Record r = Db.findFirst("select * from t_sendemail where status = 0 and num < 3");//从数据库中查到一条满足要求的记录
if (r!=null) {
String id = r.get("id").toString();
boolean a = SendEmail.sendMessage(r.getStr("email"), r.getStr("title"), r.getStr("content"));//调用核心类的sendMessage方法
if (a) {
Db.update("update t_sendemail set status = 1 where id = ?",id);
}else{
Db.update("update t_sendemail set num = num + 1 where id = ? ",id);
Db.update("update t_sendemail set status = 2 where num = 3 ");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、JmwywTimerListener类(定时不断的执行SentEmail):
package com.jmwyw.timer;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
public class JmwywTimerListener implements ServletContextListener {
private static final Logger log = Logger.getLogger(ServletContextListener.class);
private Timer shortTimer = null; //测试跑批线程
private Timer email = null; //测试跑批线程
public void contextDestroyed(ServletContextEvent arg0) {
if ( shortTimer != null ){
shortTimer.cancel();
}
log.info("定时线程中止");
}
public void contextInitialized(ServletContextEvent event) {
try {
if ( shortTimer == null ){
// shortTimer = new Timer(true);
// shortTimer.schedule(new ShortTimer(), 53*1000, 5000); //五秒一次
email = new Timer(true);
email.schedule(new SentEmail(), 53*1000, 1000*60*30); //半小时一次
log.info("定时线程启动成功。");
}
} catch (Exception e) {
log.error("定时线程启动失败" );
}
}
}