struts2+spring发送mail

需要struts和spring的框架外,还需要mail.jar,activation.jar.

javamail:   http://java.sun.com/products/javamail/downloads/index.html ,其中包括mail.jar和文档

Activation.jar : http://java.sun.com/products/javabeans/jaf/downloads/index.html ,其中包括Activation.jar

1) 首先在applicationContext.xml文件中配置bean
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="host"/>
        <property name="username" value="username"/>
        <property name="password" value="password"/>
    </bean>

<bean id="sendMailAction" class="cn.com.action.SendMailAction" singleton="false">
     <property name="mailSender"><ref bean="mailSender"/> </property>
</bean>


2)实现发送邮件java类代码

protected JavaMailSenderImpl mailSender;

public void setMailSender(JavaMailSenderImpl mailSender) {
   this.mailSender = mailSender;
}

public void sendMail() throws Exception {

1:简单邮件

     //build message
     SimpleMailMessage mailMessage = new SimpleMailMessage(); 
     mailMessage.setTo("[email protected]");
     mailMessage.setFrom("[email protected]");
     mailMessage.setSubject("test"); 
     mailMessage.setText("test send mail!!!");

     //send mail
     mailSender.send(mailMessage);

2:HTML邮件的发送
//建立邮件消息,发送简单邮件和html邮件的区别 
     MimeMessage mailMessage = senderImpl.createMimeMessage(); 
     MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); 
                 
    //设置收件人,寄件人 
     messageHelper.setTo("[email protected]"); 
     messageHelper.setFrom("[email protected]"); 
     messageHelper.setSubject("测试HTML邮件!"); 
    //true 表示启动HTML格式的邮件 
     messageHelper.setText("<html><head></head><body><h1>hello!!zhangjian</h1></body></html>",true); 
     
    //发送邮件 
     senderImpl.send(mailMessage); 

3:本类测试邮件中嵌套图片

//建立邮件消息,发送简单邮件和html邮件的区别 
     MimeMessage mailMessage = senderImpl.createMimeMessage(); 
    //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,         
multipart模式 
     MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); 
     
    //设置收件人,寄件人 
     messageHelper.setTo("[email protected]"); 
     messageHelper.setFrom("[email protected]"); 
     messageHelper.setSubject("测试邮件中嵌套图片!!"); 
    //true 表示启动HTML格式的邮件 
     messageHelper.setText("<html><head></head><body><h1>hello!!zhangjian</h1>" + 
        "<img src=\"cid:aaa\"/></body></html>",true); 
            
     FileSystemResource img = new FileSystemResource(new File("c:/aaa.jpg")); 
     
     messageHelper.addInline("aaa",img); 
     
    //发送邮件 
     senderImpl.send(mailMessage); 

}
 

你可能感兴趣的:(java,spring,html,bean,struts)