使用spring发送邮件例

做了个spring发送纯文本文件以及发送带附件的邮件的例子,共享之。
      1. SpringMail类
     

import  org.springframework.context.ApplicationContext;
import  org.springframework.context.support.FileSystemXmlApplicationContext;
import  org.springframework.mail.SimpleMailMessage;
import  org.springframework.mail.javamail.JavaMailSender;
import  org.springframework.mail.javamail.MimeMessagePreparator;

import  javax.mail.internet.MimeMessage;
import  javax.mail.MessagingException;
import  javax.mail.Message;
import  javax.mail.internet.InternetAddress;
import  javax.activation.FileDataSource;
import  javax.activation.DataHandler;
import  javax.mail.internet.MimeMultipart;
import  javax.mail.internet.MimeBodyPart;
import  javax.mail.Multipart;

import  java.util.List;
import  java.util.ArrayList;
import  java.util.Date;
import  java.util.Iterator;

/** */ /**
 * spring的邮件发送例子
 * 
@author Amigo Xie([email protected])
 * 
@since 2007/04/28 11:30
 
*/

public   class  SpringMail  {

    
public static void main(String[] args) throws Exception {
        ApplicationContext ctx 
= new FileSystemXmlApplicationContext(
                
"src/applicationContext.xml");
        JavaMailSender sender 
= (JavaMailSender) ctx.getBean("mailSender");
        SpringMail springMail 
= new SpringMail();
        
        
//测试发送只有文本信息的简单测试
        springMail.sendTextMail(sender);
        
        
//测试发送带附件的邮件
        springMail.sendMimeMessage(sender);
    }

    
    
/** *//**
     * 测试发送只有文本信息的简单测试
     * 
@param sender 邮件发送器
     * 
@throws Exception
     
*/

    
private void sendTextMail(JavaMailSender sender) throws Exception {
        SimpleMailMessage mail 
= new SimpleMailMessage();
        mail.setTo(
"[email protected]");
        mail.setFrom(
"[email protected]");
        mail.setSubject(
"test by amigo");
        mail.setText(
"spring Mail的简单测试");
        sender.send(mail);
        
        System.out.println(
"成功发送文本文件!");
    }

    
    
/** *//**
     * 发送带附件的邮件
     * 
@param sender 邮件发送器 
     * 
@throws Exception
     
*/

    
private void sendMimeMessage(final JavaMailSender sender) throws Exception {
        
//附件文件集合
        final List files = new ArrayList();
        MimeMessagePreparator mimeMail 
= new MimeMessagePreparator() {
            
public void prepare(MimeMessage mimeMessage) throws MessagingException {
                mimeMessage.setRecipient(Message.RecipientType.TO, 
                        
new InternetAddress("[email protected]"));
                mimeMessage.setFrom(
new InternetAddress("[email protected]"));
                mimeMessage.setSubject(
"Spring发送带附件的邮件""gb2312"); 
                
                Multipart mp 
= new MimeMultipart();
                
                
//向Multipart添加正文
                MimeBodyPart content = new MimeBodyPart();
                content.setText(
"内含spring邮件发送的例子,请查收!");
                
                
//向MimeMessage添加(Multipart代表正文)
                mp.addBodyPart(content);
                files.add(
"src/SpringMail.java");
                files.add(
"src/applicationContext.xml");
                
                
//向Multipart添加附件
                Iterator it = files.iterator();
                
while(it.hasNext()) {
                    MimeBodyPart attachFile 
= new MimeBodyPart();
                    String filename 
= it.next().toString();
                    FileDataSource fds 
= new FileDataSource(filename);
                    attachFile.setDataHandler(
new DataHandler(fds));
                    attachFile.setFileName(fds.getName());
                    mp.addBodyPart(attachFile);
                }

                
                files.clear();
                
                
//向Multipart添加MimeMessage
                mimeMessage.setContent(mp);
                mimeMessage.setSentDate(
new Date());
            }

        }
;

        
//发送带附件的邮件
        sender.send(mimeMail);
        
        System.out.println(
"成功发送带附件邮件!");
    }

}


      2. spring的配置文件
     

<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >

< beans >
    
< bean  id ="mailSender"  class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
        
< property  name ="host" >
            
< value > smtp.126.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 > xiexingxing1121 </ value >
        
</ property >
        
< property  name ="password" >
            
< value > <!--  此处填写密码  --> </ value >
        
</ property >
    
</ bean >
</ beans >


    刚才发现一bug,当附件名为中文时,会出现中文乱码问题,对sendMimeMessage方法进行了部分修改,如下:
   

               sun.misc.BASE64Encoder enc  =   new  sun.misc.BASE64Encoder();
                files.add(
" src/SpringMail.java " );
                files.add(
" src/applicationContext.xml " );
                files.add(
" src/谢星星.xml " );
                
                
// 向Multipart添加附件
                Iterator it  =  files.iterator();
             
while (it.hasNext())  {
                    MimeBodyPart attachFile 
= new MimeBodyPart();
                    String filename 
= it.next().toString();
                    FileDataSource fds 
= new FileDataSource(filename);
                    attachFile.setDataHandler(
new DataHandler(fds));
                    attachFile.setFileName(
"=?GBK?B?"+enc.encode(fds.getName().getBytes())+"?=");
                    mp.addBodyPart(attachFile);
                }
posted on 2007-04-28 13:23 阿蜜果 阅读(3394) 评论(6)   编辑   收藏 所属分类: Spring

<script type="text/javascript"></script>

<!---->

FeedBack:
#  re: 使用spring发送邮件例
2007-04-28 14:07 | 王凌华
:) 我直接用javamail也写了一个类似的东西。(ThreadPool实现的压力测试小工具),这里我有几问题:
a.
但是我用126的mailserver的时候,出现这样的错误:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.126.com, port: 25
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:855)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:156)
at javax.mail.Service.connect(Service.java:256)
at javax.mail.Service.connect(Service.java:135)
at javax.mail.Service.connect(Service.java:87)
at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:93)
at MailSender.run(MailSender.java:172)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)


我用我公司的的两台mailserver都可以顺畅的发mail。

   回复   更多评论
  
#  re: 使用spring发送邮件例[未登录]
2007-04-28 15:03 | ronghai
看看是不是需要SSl验证   回复   更多评论
  
#  re: 使用spring发送邮件例
2007-04-29 12:47 | 王凌华
据我所知,gmail的发送和接受是需要ssl验证的.

所以我刚才花了点时间去看了一下javamail里面ssl里面是怎么写的.
这是代码片段:

----------------------------------------------------------------------------------
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.socketFactory.fallback", "false");
// props.put("mail.smtp.debug", "true");
prop.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtps.auth", needAuth);
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.host", mailServer);
----------------------------------------------------------------------------------

----------------------------------------------------------------------------------
SMTPTransport transport = (SMTPTransport) session
.getTransport("smtps");
----------------------------------------------------------------------------------
我的努力换来的是发送期间的TimeOut, 没有任何迹象表明代码哪里有问题.
... ... ...

最后我终于明白这里用到了465 port. 而我在公司内网内,这个port默认情况下是禁用的. :) -真倒霉.   回复   更多评论
  
#  re: 使用spring发送邮件例
2007-04-29 12:50 | 王凌华
顺便贴出gmail的配置URL. 大家有兴趣也可以试试:

http://mail.google.com/support/bin/answer.py?answer=13287   回复   更多评论
  
#  spring发送内嵌邮件的图片无法正常显示的问题
2007-09-14 08:27 | LG
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;



public class SpringMail {
public static void main(String[] args) throws Exception{

ApplicationContext ctx=new FileSystemXmlApplicationContext("src/applicationContext.xml");

JavaMailSenderImpl sender = (JavaMailSenderImpl)ctx.getBean("mailSender");


SpringMail springMail=new SpringMail();

springMail.sendInit(sender);
}

private void sendInit(JavaMailSenderImpl sender) throws MessagingException {

MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true,"GB2312");
helper.setFrom("[email protected]");
helper.setTo("[email protected]");
helper.setSubject("Test");
helper.setText("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body><h1><a href='#'>郁闷!"
+ "<img src=\"cid:identifier\"></body></html>", true);

FileSystemResource res = new FileSystemResource(new File("c:/weiyi.jpg"));
helper.addInline("identifier", res);


try {
sender.send(message);
} catch (MailException e) {
e.printStackTrace();
}
System.out.println("成功发送内嵌文件");
}
}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "

你可能感兴趣的:(java,spring,bean,xml,Gmail)