本篇是通过spring框架+JSF来实现发送邮件的功能,我使用的工具是Spring Tool Suit
一、
首先先把邮件封装成一个实体类
发送邮件实体类:
public class Mail {
private String email;
private String title;
private String content;
//private long userId;
//private String userName;
private long sendTime;
private int failCount = 0;
private boolean status = false;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public int getFailCount() {
return failCount;
}
public void incFailCount(){
failCount++;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getSendTime() {
return sendTime;
}
public void setSendTime(long sendTime) {
this.sendTime = sendTime;
}
}
二、
1.写一个发送邮件的接口
import java.util.List;
import cn.company.common.model.Mail;
public interface IMailService {
//把邮件存储到队列中
public void addMail(String receiver, String title, String content);
//通过定时任务时时调用该方法发送邮件
public void doSend();
//把邮件list先储存到队列中,统一通过定时任务调用doSend方法来发送短信
public void addMails(List<Mail> mails);
}
2.实现上面的接口;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import cn.company.common.RegexConstant;
import cn.company.common.dao.MailDao;
import cn.company.common.message.MailSender;
import cn.company.common.model.Mail;
import cn.company.common.service.IMailService;
import cn.company.common.util.RegexKit;
@Service("MailService")
public class DefaultMailServiceImpl implements IMailService {
private static final Logger log = Logger
.getLogger(DefaultMailServiceImpl.class);
通过spring框架,从容器中获取到类MailSender(该类先继承了JavaMailSender,然后通过spring set注入)
@Autowired
@Qualifier("mailSender")
private MailSender sender;
//@Autowired
//@Qualifier("mailDao")
//private MailDao mailDao;
//是邮箱的正则表达式
public String REGEX_USER_EMAIL = "(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)";
private Queue<Mail> mails = new LinkedList<Mail>();
//判断是否是格式邮箱
public boolean patternTest(String pattern, String value) {
Pattern ptn = Pattern.compile(pattern);
Matcher matcher = ptn.matcher(value);
return matcher.matches();
}
private synchronized void addMessage(Mail mail) {
this.mails.add(mail);
}
private synchronized Mail getMessage() {
if (!mails.isEmpty()) {
Mail msg = mails.poll();
return msg;
}
return null;
}
@Override
public void addMail(String receiver, String title, String content) {
Mail m = new Mail();
m.setEmail(receiver);
m.setTitle(title);
m.setContent(content);
addMessage(m);
}
@Override
public void doSend() {
Mail msg = null;
while (null != (msg = getMessage())) {
if (!patternTest(REGEX_USER_EMAIL, msg.getEmail()))
{
continue;
}
MimeMessage mm = sender.createMimeMessage();
msg.setSendTime(System.currentTimeMillis());
MimeMessageHelper help;
try {
mm.setSubject(msg.getTitle());
help = new MimeMessageHelper(mm, true, "UTF-8");
help.setFrom(sender.getSenderAddress());
help.setTo(msg.getEmail());
help.setSubject(msg.getTitle());
help.setText(msg.getContent(), true);
sender.send(mm);
msg.setStatus(true);
//log.debug("Send Mail OK!");
} catch (MessagingException e) {
log.debug(e.getMessage());
msg.setStatus(false);
}
//mailDao.saveEmail(msg);
}
}
@Override
public void addMails(List<Mail> mails) {
this.mails.addAll(mails);
}
}
三、
实现把实现类DefaultMailSenderImpl纳入到spring容器中,以便在别的类中可以通过注解的方式很方便的直接调用,同时把一些必要的属性注入到该实现类中。该处要先写上配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<context:property-placeholder location="classpath:mail.properties" ignore-unresolvable="true" />
<bean id="mailSender" class="cn.company.common.message.impl.DefaultMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="port" value="${mail.port}" />
<property name="username" value="${mail.userAccount}" />
<property name="password" value="${mail.userPassword}" />
<property name="senderAddress" value="${mail.senderAddress}" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
</beans>
四、
第三步中要用到一个配置文件mail.properties,在该文件中的内容如下:
#邮箱服务器
mail.host=XXXX
mail.port=25
#自己的邮箱
mail.userAccount=XXX@qq.com
自己邮箱的密码
mail.userPassword=****
mail.authentication=true
mail.senderAddress=XXXX@qq.com
五、
1.写一个接口
import org.springframework.mail.javamail.JavaMailSender;
public interface MailSender extends JavaMailSender {
public String getSenderAddress();
}
2.实现上面接口
import org.springframework.mail.javamail.JavaMailSenderImpl;
import cn.company.common.message.MailSender;
public class DefaultMailSenderImpl extends JavaMailSenderImpl implements
MailSender {
private String senderAddress;
public String getSenderAddress() {
return senderAddress;
}
public void setSenderAddress(String senderAddress) {
this.senderAddress = senderAddress;
}
}
六、
调用发送邮件方法的封装
import java.util.List;
import cn.company.common.model.Mail;
import cn.company.common.model.SmsMessage;
import cn.company.common.service.ISmsService;
public class SmsKit {
private static ISmsService smsService = AirScapeApplicationContext.getBean("SmsService", ISmsService.class);
//private static ISmsService smsService = AirScapeApplicationContext.getBean("SmsService", ISmsService.class);
/**
* 发送注册成功消息
*
* @param receiver
*/
public static void sendMessage(String mobile, String content) {
smsService.addMessage(mobile, content);
}
public static void sendBatchMessages(List<SmsMessage> messages)
{
smsService.addMessages(messages);
}
}
七、
调用方法,发送邮件(注意,调用该方法的时候时间还没发送,要等到定时任务时间到了之后,这些存在Queue中的邮件一并发送)
public class Example{
MailKit.sendMail(XXX@q63.com,
"哈哈";"你好");
}
八、
然后在调用定时任务,在定时任务里调用doSent()方法
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import cn.company.common.service.IMailService;
import cn.company.common.service.IMonitorService;
/**
*
* @author hzh
*
*/
@Component("SendMailTask")
public class SendMailTask {
private static final Logger log = Logger.getLogger(SendMailTask.class);
@Autowired(required = true)
@Qualifier("MailService")
private IMailService mailService;
public void work() {
mailService.doSend();
}
}
九、
定时任务是写在配置文件里的(通过该配置文件,spring容器会时时调用doSend方法),如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="cn.company.task" />
<!-- 系统监控调度器 -->
<task:scheduler id="sysScheduler" pool-size="2" />
<!-- 监控任务列表 -->
<task:scheduled-tasks scheduler="sysScheduler">
<!-- 系统负载 -->
<task:scheduled ref="MgmtSystemLoadMonitorTask" method="work" cron="* */5 * * * *"/>
<!-- 发邮件 -->
<task:scheduled ref="SendMailTask" method="work" cron="*/30 * * * * *"/>
<task:scheduled ref="SendSmsTask" method="work" cron="*/15 * * * * *"/>
<!-- 发短信 -->
</task:scheduled-tasks>
</beans>