邮件服务,一直是J2EE框架的一个很重要的功能组件。那么如何进行搭建这个邮件服务的组件呢,特别是你使用了spring框架的时候,如何搭建邮件服务?这是我在下面要进行说明的。
使用spring搭建邮件服务,首先你需要对spring有一定的了解。这里,我不多说了
你找到spring的配置文件applicationContext.xml,在里面添加如下代码:
<import resource="classpath*:spring/**/*.xml" />
import进去的资源地址,是spring文件夹下面的所有以.xml结尾的文件
目录结构,你可以参考这个
下面,我们在resource/spring文件夹下面新建一个名称为:spring-mail.xml的配置文件,在里面添加如下代码
<bean id="mimeMessage" class="javax.mail.internet.MimeMessage" factory-bean="javaMailSender"
factory-method="createMimeMessage" />
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.sina.com" />
<property name="username" value="[email protected]" />
<property name="password" value="yourpassword" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.host">smtp.sina.com</prop>
<prop key="mail.smtp.timeout">25000</prop>
<!-- <prop key="mail.smtp.port">25</prop>
<prop key="mail.smtp.socketFactory.port">25</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
-->
</props>
</property>
</bean>
<bean id="mailService" class="com.core.base.mail.service.impl.MailServiceImpl">
<property name="mailSender" ref="javaMailSender" />
<property name="mimeMessage" ref="mimeMessage" />
</bean>
注意,我使用的是新浪的邮箱,如果你不是使用新浪邮箱,请修改host的value
这个时候,spring的配置文件就写好了,接下来,我们看看具体的java代码如何实现吧
第一个java类:MailModel
package com.core.base.mail.model;
/**
* 邮件model
* @author Administrator
*
*/
public class MailModel {
private String fromAddress;//发送人地址1个
private String toAddresses;//接收人地址,可以为很多个,每个地址之间用";"分隔,比方说[email protected];[email protected]
private String subject;//邮件主题
private String content;//邮件文本内容
private String[] attachFileNames;//附件
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getToAddresses() {
return toAddresses;
}
public void setToAddresses(String toAddresses) {
this.toAddresses = toAddresses;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public void setAttachFileNames(String[] attachFileNames) {
this.attachFileNames = attachFileNames;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
}
【这个类是邮件的model,包含了发送邮件的一些需要的属性】
第二个类:MailServiceImpl,这个类是继承的MailService接口。具体的模式我是跟ssh框架开发差不多的结构
package com.core.base.mail.service.impl;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.core.base.mail.model.MailModel;
import com.core.base.mail.model.MailSenderInfo;
import com.core.base.mail.service.MailService;
import com.core.base.util.mail.MyAuthenticator;
public class MailServiceImpl implements MailService {
private JavaMailSender mailSender;
private MimeMessage mimeMessage;
private static Logger logger = Logger.getLogger(MailServiceImpl.class);
/**
* 发送html格式的,带附件的邮件
*/
@Override
public void sendAttachMail(MailModel mail) {
try {
MimeMessageHelper mailMessage = new MimeMessageHelper(
this.mimeMessage, true, "UTF-8");
mailMessage.setFrom(mail.getFromAddress());// 设置邮件消息的发送者
mailMessage.setSubject(mail.getSubject());// 设置邮件消息的主题
mailMessage.setSentDate(new Date());// 设置邮件消息发送的时间
mailMessage.setText(mail.getContent(), true); // 设置邮件正文,true表示以html的格式发送
String[] toAddresses = mail.getToAddresses().split(";");// 得到要发送的地址数组
for (int i = 0; i < toAddresses.length; i++) {
mailMessage.setTo(toAddresses[i]);
for (String fileName : mail.getAttachFileNames()) {
mailMessage.addAttachment(fileName, new File(fileName));
}
// 发送邮件
this.mailSender.send(this.mimeMessage);
logger.info("send mail ok=" + toAddresses[i]);
}
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}
}
通过这个servieimpl,可以实现发现邮件
最后,我们来进行一个测试,这里还要进行一个说明,项目采用的是SSH框架
为了方便,我也不考虑那么多了,当用户进行登录系统的时候,给他发一封邮件通知他。
a.在UserAction里面,注入mailService。
package com.neweducation.user.action;
import com.core.base.action.BaseAction;
import com.core.base.mail.model.MailModel;
import com.core.base.mail.service.impl.MailServiceImpl;
import com.neweducation.user.model.UserModel;
import com.neweducation.user.service.UserService;
import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends BaseAction implements ModelDriven<UserModel> {
/**
*
*/
private static final long serialVersionUID = 1L;
private UserService userService;
private UserModel userModel = new UserModel();
private MailServiceImpl mailService;
/**
* 登录
*
* @return
*/
public String userLogin() {
UserModel user = userService.loginJudge(userModel.getUserName(),
userModel.getUserPass());
if (user != null) {
MailModel mm = new MailModel();
String fileNames[] = { "e:/xx.txt" };
mm.setAttachFileNames(fileNames);
mm.setFromAddress("[email protected]");
mm.setToAddresses("[email protected];[email protected]");
mm.setContent("在做项目的过程中,我们经常会遇到这样的情况,需要进行单点登录<br/>,也就是说用户登录一个系统的同时也登录到其他系统。<br/> ");
mm.setSubject("这是一个spring整合javamail的测试");
mailService.sendAttachMail(mm);
return SUCCESS;
} else {
return INPUT;
}
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserService getUserService() {
return userService;
}
@Override
public UserModel getModel() {
return getUserModel();
}
public void setUserModel(UserModel userModel) {
this.userModel = userModel;
}
public UserModel getUserModel() {
return userModel;
}
public void setMailService(MailServiceImpl mailService) {
this.mailService = mailService;
}
public MailServiceImpl getMailService() {
return mailService;
}
}
b.修改spring-bean-user.xml配置文件的内容,以实现mailService的注入
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
default-lazy-init="true" default-autowire="byName">
<bean id="UserAction" class="com.neweducation.user.action.UserAction"
scope="prototype">
<property name="userService" ref="userService" />
<property name="mailService" ref="mailService" />
</bean>
<bean id="userService" class="com.neweducation.user.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
<bean id="userDao" class="com.neweducation.user.dao.UserDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
自己写一个login。jsp,实现登录就可以了