1.用spring的mail發(fā)郵件需要將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上就會出現(xiàn)上面的錯誤,因為javaEE5中包含有javaMail的類但是卻不全面,所以造成與本身的JavaMail包沖突。而activation1.0.2與1.1版本也不同,LogSupport在1.0.2中沒有。
3.各個郵件服務(wù)器的驗證可能不一定都能通過,多換幾個試試。
4.發(fā)送簡單郵件可以使用SimpleMailMessage類
5.發(fā)送帶附件的郵件可以使用MimeMessage+MimeMessageHelper。
6.如果要發(fā)送html格式的內(nèi)容,MimeMessageHelper中的方法setText("需要發(fā)送的html格式的內(nèi)容",true)
7.如果在容器中使用spring發(fā)送郵件的話,在讀取配置文件的時候,因為容器的特殊性,不需要使用 ApplicationContext ctx = new FileSystemXmlApplicationContext( "src/mail-config.xml") ,可以使用ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext())來獲取ctx。在容器初始化的時候?qū)⑦@個ctx獲取之后存在某個靜態(tài)變量中去。在使用的時候再根據(jù)這個ctx去獲取相應(yīng)的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 <xrzp_dh@yahoo.com.cn>
*/

public class SendMail {

// 將郵件頁面的參數(shù)按照map的形式放入
private Map<String, String> parameters = new HashMap<String, String>();

// 分隔符
private final static String fileSeparator = System
.getProperty("file.separator");


/**
* 發(fā)送帶附件的郵件
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void sendMail(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {
//因為直接是在容器中.故使用BeanManager將相應(yīng)的bean獲取,再造型成JavaMailSender
JavaMailSender sender = (JavaMailSender) BeanManager
.getBean("mailSender");

request.setCharacterEncoding("UTF-8");
//添加附件到服務(wù)器
File file = this.doAttachment(request);

MimeMessage msg = sender.createMimeMessage();

try {
MimeMessageHelper helper = new MimeMessageHelper(msg, true,
"GB2312");
//發(fā)送到哪兒
helper.setTo(parameters.get("to"));
//誰發(fā)送的
helper.setFrom(parameters.get("from"));
//發(fā)送的主題
helper.setSubject(parameters.get("subject"));
//發(fā)送的內(nèi)容
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();
}

}


/**
* 發(fā)送簡單郵件
* @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("xxxx@qq.com");
mail.setFrom("xxxx@163.com");
mail.setSubject("dosth by xxx");
mail.setText("springMail的簡單發(fā)送測試");
sender.send(mail);

} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 添加附件
* 在添加附件的時候,可以將表格想對應(yīng)的參數(shù)放到一個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());
//將附件上傳到服務(wù)器
item.write(file);
}
}
}

} catch (Exception e) {
e.printStackTrace();
}
return file;
}
}

2.BeanManager類
import org.springframework.context.ApplicationContext;

/**
* @author zpruan
* @mail <xrzp_dh@yahoo.com.cn>
*/

public class BeanManager {

// 應(yīng)用上下文環(huán)境對象
private static ApplicationContext ac = null;

/**
* 利用Spring實現(xiàn)聲明式依賴注入,便于直接獲取bean對象
*/

public static ApplicationContext getApplicationContext() {
return ac;
}


/**
* 返回Spring的ApplicationContext對象
*
* @return
*/

public static void setApplicationContext(ApplicationContext acObj) {
ac = acObj;
}


/**
* 根據(jù)指定的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>
posted on 2008-10-18 16:18
xrzp 閱讀(2722)
評論(4) 編輯 收藏 所屬分類:
JAVA