spring email 电子邮件发送

额外Jar : activation.jar 和mail.jar

第一步 xml配置spring Bean

    <!-- spring 发送Email的配置 --> 
   <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
      <property name="host" value="mail.aa.com" />
      <property name="username" value="[email protected]" />
      <property name="password" value="aaaa" />
      <property name="javaMailProperties">
      <props>
         <prop key="mail.smtp.auth">true</prop>
       </props>
       </property>
    </bean>

   <!-- 邮件服务接口类 20110601 -->
    <bean id="mailSendService" class="com.interaction.service.MailSendService">
        <property name="mailSender" ref="mailSender" />
        <property name="form" value="[email protected]"/>
    </bean>

接口实现

 

/**
 * 文件名  :SimpleMailService.java
 * 创建日期 :Jun 1, 2011
 * Copyright (c) 2003-2011 
 * All rights reserved.
 */
package com.interaction.service;

import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 描述:电子邮件发送接口
 * 目前支持文本格式、HTML格式的内容形式
 * @version 1.00
 * Spring Bean 参数配置在中
 * @author  *
 */
public class MailSendService {
 
 private static Logger logger = Logger.getLogger(MailSendService.class);
 
    public String form;
   
    private JavaMailSender mailSender;


 /**
  * 以普通文本的格式发送Email
  * @param to  发送给谁,对应的email
  * @param title  邮件主题
  * @param message  邮件内容  支持普通文本
  * @throws Exception
  */
 public void sendSimpleEmail(String to,String title, String message) throws Exception
    {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(form);
        msg.setTo(to);
        msg.setSubject(title);
        msg.setText(message);

        try{
            mailSender.send(msg);
            logger.info( form+",文本格式内容邮件已发送至:"+to);
        }catch (Exception e){
            logger.error("发送邮件失败", e);
            throw e;
        }
    }
 
 /**
  * 支持HTML脚本的格式发送Email
  * @param to  发送给谁,对应的email
  * @param title  邮件主题
  * @param message  邮件内容  支持HTML脚本
  * @throws Exception
  */
 public void sendHtmlEmail(String to,String title, String message) throws Exception
    {
  MimeMessage msg = mailSender.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(msg, true, "GB2312");
  helper.setTo(to);
  helper.setFrom(form);
  helper.setSubject(title);
  helper.setText(message, true);
  
  try{
         mailSender.send(msg);
         logger.info( form+",HTML格式内容邮件已发送至:"+to);
      }catch (Exception e){
         logger.error("发送邮件失败", e);
         throw e;
        }
    }
 
 
 public String getForm() {
  return form;
 }

 public void setForm(String form) {
  this.form = form;
 }
 public JavaMailSender getMailSender() {
  return mailSender;
 }
 public void setMailSender(JavaMailSender mailSender) {
  this.mailSender = mailSender;
 }

 

}

你可能感兴趣的:(spring,bean,log4j,xml,脚本)