姿姿霸霸~~!
贵在坚持!
posts - 106,  comments - 50,  trackbacks - 0

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  <xrzp_dh@yahoo.com.cn>
 
*/

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(
"xxxx@qq.com");
        mail.setFrom(
"xxxx@163.com");
        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  <xrzp_dh@yahoo.com.cn>
 
*/

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>
posted on 2008-10-18 16:18 xrzp 阅读(2700) 评论(4)  编辑  收藏 所属分类: JAVA

FeedBack:
# re: 使用spring发送邮件
2008-10-19 23:36 | 杨爱友
用你的办法我没有得到ApplicationContext对象,我改用new ClassPathXmlApplicationContext("applicationContext.xml")获取。  回复  更多评论
  
# re: 使用spring发送邮件
2008-10-19 23:58 | 杨爱友
你xml文件里的用户名和密码指的是发送者邮箱,可当一个系统投入使用时,这个发送者肯定是当前用户,所以我觉得发送者的用户名和密码不应该设置在xml文件,应该是从前台获取,然后再设置到JavaMailSender 对象。  回复  更多评论
  
# re: 使用spring发送邮件
2008-10-20 23:37 | sure_xx
@杨爱友
ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()) 是对容器的上下文环境的获取.我是重写了DispatcherServlet类,放到init方法中去获取,然后再set到beanManager中去的.  回复  更多评论
  
# re: 使用spring发送邮件
2008-10-20 23:40 | sure_xx
@杨爱友
你说的很对哈.如果是个系统的话,登陆之后就有自己的用户名和密码.可以将JavaMailSender sender = (JavaMailSender) BeanManager.getBean("mailSender");改为JavaMailSenderImpl sender = (JavaMailSenderImpl)BeanManager.getBean("mailSender");再通过sender的setUsername和setPassword来将用户名和密码搞进去.
  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 

<2008年10月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

常用链接

留言簿(4)

随笔分类

随笔档案

好友的blog

搜索

  •  

积分与排名

  • 积分 - 115106
  • 排名 - 505

最新评论

阅读排行榜

评论排行榜