spring框架发送邮件(单发,群发,发送多个附件)

前言:发送邮件是常用技术,主流框架springboot整合的邮件发送非常简单好用(想了解的从这里可以传送),传统的javamail这里也不做介绍(想了解的从这里传送,现在都用框架开发所以也不怎么用的上),我现在做的项目是基于jeecg框架,所以这里以spring框架整合javamail邮箱服务器为qq为例。


1.项目是基于maven构建的spring项目(基本的依赖这里就不说了),引入mail的依赖

<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4</version>
		</dependency>

2.在项目的resources中新建mail.properties文件,加入如下配置(这里的参数不了解可以点击第二个传送门,或者自行百度一下)

mail.host=smtp.qq.com  //qq邮箱服务器
mail.username=发送人邮箱
mail.password=生成的授权码
mail.smtp.auth=true   //认证
mail.smtp.timeout=25000  //超时
mail.smtp.port=25 //端口

3.在项目的resources中新建mail.xml文件,加入如下配置内容(最下面那个mailutil是我建的工具类,根据情况替换成你们建的类的路径跟名称)

<?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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        ">
    <!-- 引入属性文件 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:mail.properties" />

    <!-- 邮件发送器   -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.host}" />
        <property name="username" value="${mail.username}" />
        <property name="password" value="${mail.password}" />
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
                <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
                <prop key="mail.smtp.port">${mail.smtp.port}</prop>
            </props>
        </property>
    </bean>

    <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
        <!-- 发件人email -->
        <property name="from" value="${mail.username}" />
    </bean>

    <bean id="mailUtil" class="org.jeecgframework.core.util.MailUtil">
        <property name="mailSender" ref="mailSender"></property>
        <property name="simpleMailMessage" ref="simpleMailMessage"></property>
    </bean>
</beans>

4.在你项目的spring-mvc.xml中引入mail.xml文件

5.下面是代码部分

package org.jeecgframework.core.util;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MailUtil {

    private JavaMailSenderImpl mailSender;

    private SimpleMailMessage simpleMailMessage;


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

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
        this.simpleMailMessage = simpleMailMessage;
    }

    /**
     * 单发
     *
     * @param recipient 收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendToOne(String recipient,String subject,String content){
        simpleMailMessage.setTo(recipient);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        mailSender.send(simpleMailMessage);
    }

    /**
     * 群发
     *
     * @param recipients 收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendToMore(List<String> recipients, String subject, String content){
        simpleMailMessage.setTo(recipients.toArray(new String[recipients.size()]));
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        mailSender.send(simpleMailMessage);
    }

    /**
     * 群发多个附件
     */
    public void sendWithFiles(List<String> recipients, String subject, String content, InputStream bzwbIo,InputStream bzsmIo, String opinionPath){

        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(msg, true);
            helper.setFrom(mailSender.getUsername());
            helper.setSubject(subject);
            BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
            mdp.setContent(content, "text/html;charset=UTF-8");// 给BodyPart对象设置内容和格式/编码方式
            Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对象
            mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
            // 把mm作为消息对象的内容
            //征求意见表附件
            MimeBodyPart opinion = new MimeBodyPart();
            FileDataSource filedatasource = new FileDataSource(opinionPath);
            opinion.setDataHandler(new DataHandler(filedatasource));
            try {
                opinion.setFileName(MimeUtility.encodeText(filedatasource.getName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            mm.addBodyPart(opinion);
            //标准文本
            if (bzwbIo != null) {
                MimeBodyPart bzwb = new MimeBodyPart();
                DataSource dataSource=new ByteArrayDataSource(bzwbIo, "application/octet-stream");
                bzwb.setDataHandler(new DataHandler(dataSource));
                bzwb.setFileName(MimeUtility.encodeText("标准文本.doc"));
                mm.addBodyPart(bzwb);
            }
            //编制说明
            if (bzsmIo != null) {
                MimeBodyPart bzsm = new MimeBodyPart();
                DataSource dataSource1=new ByteArrayDataSource(bzsmIo, "application/octet-stream");
                bzsm.setDataHandler(new DataHandler(dataSource1));
                bzsm.setFileName(MimeUtility.encodeText("编制说明.doc"));
                mm.addBodyPart(bzsm);
            }
            msg.setContent(mm);

            List<InternetAddress> list = new ArrayList<InternetAddress>();
            for (String recipient : recipients) {
                list.add(new InternetAddress(recipient));
            }
            InternetAddress[] address = list.toArray(new InternetAddress[list.size()]);
            msg.setRecipients(Message.RecipientType.TO,address);
            msg = helper.getMimeMessage();
            mailSender.send(msg);
            bzwbIo.close();
            bzsmIo.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

这里解释一下我的代码中的参数含义

1.List<String> recipients  接收人的邮箱集合

2.subject  邮件主题

3.content 邮件正文

4.  InputStream bzwbIo InputStream bzsmIo  String opinionPath 前面两个参数是我从ftp上获取的附件的数据流,因为我的邮件发送功能发送的附件分两种,一种是项目中的附件,另一种是上传到ftp文件服务器上的附件,所以这里的附件参数有两种,一种是这种数据流,另一种是附件在本项目中的路径,注意数据流和路径发送时候的区别,一个是FileDataSource filedatasource = new FileDataSource(opinionPath);另一个是DataSource dataSource=new ByteArrayDataSource(bzwbIo, "application/octet-stream");

6.进行测试

 

reviewProject.getLetteReview()是文件在ftp服务器上的存储路径,邮箱必须填写有效邮箱,不然会报错,我这里只写一个例子,主题正文根据需求来,数据流看你是否需要,不需要可以删除这个参数和方法中对应的代码,项目中的附件路径根据你存放的位置,根据相应的方法获取,一般都是放在webapp下面,通过request.getSession().getServletContext().getRealPath("/")+附件路径包路径获取。获取数据流的方法我这里就不贴了就是通过ftpclient连接ftp服务器通过路径获取数据流,可自行百度。

7.上面的代码是我的需求和使用场景,只是邮件的部分应用,可根据情况copy可用部分。 

如有疑问,欢迎留言讨论!

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值