Java邮件服务学习之四:邮箱服务客户端Spring Mail

一、Spring Mail API

  Spring邮件抽象层的主要包为org.springframework.mail,Spring提供的邮件发送不仅支持简单邮件的发送、添加附件。

1、邮件发送的核心接口:MailSender,实现类JavaMailSenderImpl;
2、邮件对象:SimpleMailMessage 封装了简单邮件的属性如from, to,cc, subject,text;
org.springframework.mail.javamail.JavaMailSender和org.springframework.mail.javamail.MimeMessagePreparator, 用于准备JavaMail的MIME信件。

引入相关jar包:spring 相关jar包  mail.jar 和 activation.jar

二、Spring mail 发送邮件

1、配置

(1)mail.properties

# mail host
mail.host=smtp.163.com
# smtp port
mail.port=25
mail.encoding=UTF-8
mail.smtp.auth=true
# request timeout
mail.smtp.timeout=25000
mail.username=cac2020@163.com
mail.password=123456
mail.from=email@163.com;

(2)spring-mail.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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- 扫描该包下的Bean -->
     <context:component-scan base-package="com.jeecg.mail" /> 
    
    <!-- 加载Properties文件 -->  
    <context:property-placeholder location="classpath:mail.properties" />
    
    <!-- 邮件发送 -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host">
            <value>${mail.host}</value>
        </property>
        <property name="username">
            <value>${mail.username}</value>
        </property>
        <property name="password">
            <value>${mail.password}</value>
        </property>
        <property name="port">
            <value>${mail.port}</value>
        </property>
        <property name="defaultEncoding">
            <value>${mail.encoding}</value>
        </property>
        <property name="protocol">
            <value>smtp</value>
        </property>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
                <!-- <prop key="mail.smtp.starttls.enable">true</prop> 取决于使用的邮件服务是否支持STARTTLS加密 -->
                <!-- <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> 取决于是否使用SSL端口发送邮件-->
                <prop key="mail.smtp.socketFactory.fallback">false</prop>
                <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
<!--                 <prop key="mail.sendTo">${mail.sendTo}</prop> -->
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>
    
    <!-- 异步线程 -->
    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="10" />
        <property name="maxPoolSize" value="30" />
    </bean>
</beans>

(3)发送邮件

package com.jeecg.mail.controller;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jeecg.mail.service.MailServiceImpl;

@Scope("prototype")
@Controller
@RequestMapping("/MailController")
public class MailController extends BaseController
{
    @Autowired
    private MailServiceImpl mailService;
    
    
    @RequestMapping(params = { "mail", "page" })
    public ModelAndView mail(@RequestParam("page") String page,HttpServletRequest request) 
    {
        ModelAndView modelAndView = new ModelAndView(page);
        return modelAndView;
    }
    
    @RequestMapping(params = "sendTextMail", method = { RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public AjaxJson sendTextMail()
    {
        AjaxJson json = new AjaxJson();
        try 
        {
            mailService.sendTextMail("cac2020@163.com", "530589482@qq.com", "cac2020@126.com", "【测试】发送一个纯文本邮件",
                    "哈哈哈哈哈哈  这是一个纯文本邮件");
        } 
        catch (Exception e) 
        {
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return json;
    }
    
    @RequestMapping(params = "sendHTMLMail", method = { RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public AjaxJson sendHTMLMail()
    {
        AjaxJson json = new AjaxJson();
        try 
        {
            mailService.sendHTMLMail("cac2020@163.com", "530589482@qq.com", "cac2020@126.com", "【测试】发送一个HTML邮件", 
                    "<html><head></head><body><h1>hello!!spring html Mail</h1></body></html>");
        } 
        catch (MessagingException e) 
        {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }
    
    @RequestMapping(params = "sendImageMail", method = { RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public AjaxJson sendImageMail(HttpServletRequest request)
    {
        AjaxJson json = new AjaxJson();
        try 
        {
            String jpgpath = request.getSession().getServletContext().getRealPath("/images/1.jpg");
            mailService.sendImageMail("cac2020@163.com", "530589482@qq.com", "cac2020@126.com", "【测试】发送一个含图片邮件",  
                    "<html><head></head><body><h1>hello!!spring image html mail</h1><img src="cid:1"/></body></html>", 
                    "1", 
                    jpgpath);
        } 
        catch (MessagingException e) 
        {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }
    
    @RequestMapping(params = "sendAttachMail", method = { RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public AjaxJson sendAttachMail(HttpServletRequest request)
    {
        AjaxJson json = new AjaxJson();
        try 
        {
            String filepath = request.getSession().getServletContext().getRealPath("/images/测试.rar");
            mailService.sendAttachMail("cac2020@163.com", "530589482@qq.com", "cac2020@126.com", "【测试】发送一个含附件邮件", 
                    "", 
                    "测试.rar", 
                    filepath);
        } 
        catch (MessagingException e) 
        {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }
    
}

注意:

1、Spring容器仅允许最多定义一个PropertyPlaceholderConfigurer(或<context:property-placeholder/>),其余的会被Spring忽略掉

Spring 配置文件中<context:property-placeholder/>标签如果有多个properties文件   location='classpath:db.properties,classpath:default.properties,classpath:default3.properties,classpath:default2.properties'

参考:

http://blog.csdn.net/smcwwh/article/details/7095027

http://blog.csdn.net/zheng0518/article/details/50179213

http://www.oschina.net/code/snippet_2416648_55116

http://blog.csdn.net/zh921112/article/details/38397801

http://blog.csdn.net/houxuehan/article/details/52184736

http://www.zgxue.com/167/1677686.html

原文地址:https://www.cnblogs.com/cac2020/p/6001512.html