1.用spring的mail发邮件需要将j2ee包里的mail.jar和activation.jar引入
2.遇见的异常可能会有
(1)java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
(2)java.lang.NoClassDefFoundError: com/sun/activation/registries/LogSupport
这2个异常都是由于JavaEE版本和JavaMail的版本不一致所造成的.如javaMail1.3以下的如果在javaEE5上就会出现上面的错误,因为javaEE5中包含有javaMail的类但是却不全面,所以造成与本身的JavaMail包冲突。而activation1.0.2与1.1版本也不同,LogSupport在1.0.2中没有。
3.各个邮件服务器的验证可能不一定都能通过,多换几个试试。
4.发送简单邮件可以使用SimpleMailMessage类
5.发送带附件的邮件可以使用MimeMessage+MimeMessageHelper。
6.如果要发送html格式的内容,MimeMessageHelper中的方法setText("需要发送的html格式的内容",true)
7.如果在容器中使用spring发送邮件的话,在读取配置文件的时候,因为容器的特殊性,不需要使用 ApplicationContext ctx = new FileSystemXmlApplicationContext( "src/mail-config.xml") ,可以使用ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext())来获取ctx。在容器初始化的时候将这个ctx获取之后存在某个静态变量中去。在使用的时候再根据这个ctx去获取相应的bean。
代码如下:
1.SendMail类
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.sureframe.BeanManager;
/**
* @author zpruan
* @mail <>
*/
public class SendMail {
// 将邮件页面的参数按照map的形式放入
private Map<String, String> parameters = new HashMap<String, String>();
// 分隔符
private final static String fileSeparator = System
.getProperty("file.separator");
/**
* 发送带附件的邮件
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void sendMail(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//因为直接是在容器中.故使用BeanManager将相应的bean获取,再造型成JavaMailSender
JavaMailSender sender = (JavaMailSender) BeanManager
.getBean("mailSender");
request.setCharacterEncoding("UTF-8");
//添加附件到服务器
File file = this.doAttachment(request);
MimeMessage msg = sender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(msg, true,
"GB2312");
//发送到哪儿
helper.setTo(parameters.get("to"));
//谁发送的
helper.setFrom(parameters.get("from"));
//发送的主题
helper.setSubject(parameters.get("subject"));
//发送的内容
helper.setText(parameters.get("content"),true);
if (file != null) {
FileSystemResource fileSource = new FileSystemResource(file
.getPath());
helper.addAttachment(file.getName(), fileSource);
}
sender.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送简单邮件
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void sendMail1(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JavaMailSender sender = (JavaMailSender) BeanManager
.getBean("mailSender");
SimpleMailMessage mail = new SimpleMailMessage();
try {
mail.setTo("");
mail.setFrom("");
mail.setSubject("dosth by xxx");
mail.setText("springMail的简单发送测试");
sender.send(mail);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 添加附件
* 在添加附件的时候,可以将表格想对应的参数放到一个map中去
* 在此使用了Jakarta commons的fileupload组件
* @param request
* @return
* @throws ServletException
* @throws IOException
*/
@SuppressWarnings({ "unchecked", "deprecation" })
public File doAttachment(HttpServletRequest request)
throws ServletException, IOException {
File file = null;
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (item.isFormField()) {
parameters.put(item.getFieldName(), item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
File tempFile = new File(item.getName());
String path = request.getRealPath(fileSeparator)
+ "uploads" + fileSeparator;
file = new File(path);
//建立个文件夹
if(!file.exists()){
file.mkdir();
}
file = new File(path, tempFile.getName());
//将附件上传到服务器
item.write(file);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
}
2.BeanManager类
import org.springframework.context.ApplicationContext;
/**
* @author zpruan
* @mail <>
*/
public class BeanManager {
// 应用上下文环境对象
private static ApplicationContext ac = null;
/**
* 利用Spring实现声明式依赖注入,便于直接获取bean对象
*/
public static ApplicationContext getApplicationContext() {
return ac;
}
/**
* 返回Spring的ApplicationContext对象
*
* @return
*/
public static void setApplicationContext(ApplicationContext acObj) {
ac = acObj;
}
/**
* 根据指定的bean名字来获取bean
*
* @param key
* @return
*/
public static Object getBean(String key) {
return ac.getBean(key);
}
}
3.xml配置
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>smtp.163.com</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
<property name="username">
<value><!-- 用户名 --></value>
</property>
<property name="password">
<value><!-- 密码 --></value>
</property>
</bean>
</beans>