`
floger
  • 浏览: 209493 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用Spring JavaMail 定时发送邮件

阅读更多

包括: 一个配置文件, 一个继承了java.util.TimerTask 的类:TimerMail.java

一 . 配置文件中使用了两个类(还可以使用更多的 类,如:org.springframework.mail.MailMessage 邮件模板.
    1. org.springframework.scheduling.timer.TimerFactoryBean
2. org.springframework.scheduling.timer.ScheduledTimerTask

<beans>
<bean id="springSendMail" class="com.yidwo.app.springMail.SpringSendMail">
   <property name="mailSender">
    <ref bean="mailSender" />
   </property>
</bean>

    <!-- 定时任务 -->
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
   <property name="scheduledTimerTasks">
    <list>
     <ref bean="springTimerTask" />
    </list>
   </property>
</bean>
<bean id="springTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
   <property name="timerTask">
    <ref bean="springSendMail" />
   </property>
   <property name="delay">
    <value>10000</value>
   </property>
   <property name="period">
    <value>3600000</value> <!-- 区间要定在一小时 3600000-->
   </property>
</bean>

    <!-- 邮件发送模板 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
   <property name="host" value="smtp解析地址" />
   <property name="port" value="25" />
   <property name="username" value="username" />
   <property name="password" value="password" />
   <!-- 如果要使用用户名和密码验证,这一步需要 -->
   <property name="javaMailProperties">
          <props>   
              <prop key="mail.smtp.auth">true</prop>
          </props>
        </property>
       
</bean>
</beans>

 

实现的类代码如下:

package com.yidwo.app.springMail;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.Locale;
import java.io.ByteArrayOutputStream;

import java.io.OutputStreamWriter;
import java.io.Writer;

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


import freemarker.template.Template;
import freemarker.template.Configuration;


/**
* 报表邮件发送类
*
* @author Yinghe Lai
*
*/
public class SpringSendMail extends TimerTask {

private static final Logger logger = Logger.getLogger(SpringSendMail.class);
public SpringSendMail() {}

private JavaMailSenderImpl mailSender;

public JavaMailSenderImpl getMailSender() {
   return mailSender;
}

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


public void run() {
  
   this.doEmail();
}
  

// 进行发送处理
private void doEmail() {
  
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   try {
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,"utf-8");

    helper.setTo("接收邮箱");   // 设置接收邮箱 邮箱必须符合邮箱格式

// 设置发送方信息,邮箱必须符合邮箱格式
    helper.setFrom("置发送邮箱", "发送人别名");

    helper.setSubject("设置标题");    // 设置标题
   
    // list 为其它程序传入, 用于动态填充模板.
    String fmStr = this.doFreemarkerMail(this.doFreemarkerMail(List list));
    helper.setText("这是您设置接收的报表邮件,请查收.",fmStr);

    mailSender.send(mimeMessage);
    helper = null;
    System.out.println("*** The required mail has been successfully sended ***");
              
   } catch (Exception e) {
    logger.debug("sendException: "+e.getMessage());
    e.printStackTrace();
   }
}
  

// 构造freemarker动态邮件

// 只要由其它方法传入一个List结构的数据就可.返回邮件内容
private String doFreemarkerMail(List list) throws Exception{
  
   Map maplist = new HashMap();
        maplist.put("mapList", list);
       
   Configuration freemarker_cfg = new Configuration();
   freemarker_cfg.setEncoding(Locale.getDefault(), "utf-8");      
  
   // 查找并加载freemarker模板文件.
     freemarker_cfg.setClassForTemplateLoading(this.getClass(), "
\\com\\yidwo\\app\\springMail");
   Template freetemplate = freemarker_cfg.getTemplate("mailTemplate.ftl");
  
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Writer out = new OutputStreamWriter(bos);     
        freetemplate.process(mapList, out);       
       
        String content = bos.toString();
        out.close();
        return content;
}

// 返回List 用于动态更新模板文件
private List returnList(){
    List list = new ArrayList();
    return list;
}

 

 

邮件开发中的异常:

1. javax.mail.MessagingException: Could not connect to SMTP host: www.d1888.com, port: 25, response: -1
   都是配置host时出错.要不没有此host的.要不服务解析时没有对应到邮件服务器.

2. org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException

   是邮箱用户名或密码出错导致.

3. com.sun.mail.smtp.SMTPSendFailedException: 503 input error.

   是setFrom时设置的邮箱出错,这里的设置要符合邮箱格式.(
user@websit.com).

分享到:
评论

相关推荐

    spring+quartz+javamail定时发送邮件

    Spring框架整合Quartz,使用javamail定时发送邮件

    在spring利用javamail,quartz定时发送邮件

    在spring利用javamail,quartz定时发送邮件

    spring--quartz的定时调度的maven部署

    NULL 博文链接:https://firezhfox.iteye.com/blog/1770575

    Spring 2.0 开发参考手册

    6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. 其它资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点实施 7.2.3. AspectJ切入点表达式 7.2.4. ...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.1.1. @Configurable object的单元测试 6.8.1.2. 多application context情况下的处理 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来...

    spring chm文档

    Spring Framework 开发参考手册 Rod Johnson Juergen Hoeller Alef Arendsen Colin Sampaleanu Rob Harrop Thomas Risberg Darren Davison Dmitriy Kopylenko Mark Pollack ...19.2. 使用Spring JMS ...

    Spring Boot+Mybatis-Plus校园二手交易平台源码.zip

    Spring Boot+Mybatis-Plus校园二手交易平台...基于 JavaMail 实现用 QQ 邮箱发送邮件;前台界面采用了Bootstrap4框架;后台界面采用了jQuery EasyUI框架;Redis存储用户购物车信息;Gson处理JSON数据;Quartz定时任务;

    Spirng Boot+Mybatis个人博客系统源码.zip

    Spirng Boot+Mybatis个人博客系统;本项目核心技术采用Spring Boot+Mybatis;开发工具idea;...基于JavaMail实现用QQ邮箱发送邮件 ;highlight.js代码高亮;Highcharts图表;Redis存储经常查看的数据。

    基于jbpm与activiti的工作流平台技术架构介绍

    ◦邮件、短信模板管理 用于配置系统的发送邮件、短信的模板 ◦工作日历管理 用于配置系统的工作流的待办事项的处理工作时间的计算处理 ◦动态脚本管理 用于为流程任务节点或事件中可被调用的逻辑计算代码 ◦短信收发...

    互联网创意产品众筹平台

    │ 03-弹层组件layer使用. [- l; o" [6 F# U# ~. a7 c │ 04-用户分页查询-分析-同步请求方式 │ 05-用户分页查询-分析-同步请求代码开发 │ 06-用户分页查询-分页导航条# a1 W7 L ^ n8 [7 F' [( g │ 07-用户分页...

Global site tag (gtag.js) - Google Analytics