发送带附件的邮件

原理:通过JavaMailSender发送带附件的邮件
1.发送邮件代码

//注入邮件发送类
@Autowired
private MyJavaMailSender sender;

/**  
	 发送邮件的方法
     * @param to 邮件接收方
     * @param subject 邮件标题
     * @param content  邮件内容
     * @param filePath  附件位置(例如: d://activityCDetailExcel/aaa.xlsx)
     * @return
     */
 public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = sender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = null;
            helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(sender.getUsername());//邮件的发送方,可以写死
            helper.setTo(to.split(","));//邮件接收方,分割逗号.实现同时发送给多个用户
            helper.setSubject(subject);
            helper.setText(content, true);
            File file = new File(filePath);
            if (file.exists()) {
                FileSystemResource tempFile = new FileSystemResource(new File(filePath));
                helper.addAttachment(MimeUtility.encodeWord(file.getName(), "utf-8", "B"), tempFile);
            }
            sender.send(message);
            return;
        } catch (Exception e) {
            logger.error("系统报错,错误信息:{}", e);
            return;
        }
    }

2.yml配置文件:配置了发送方的邮箱等相关配置信息

spring:
   mail:
    username: 15*****@qq.com
    password: z****
    properties:
      mail:
        transport:
          protocol: smtp
        smtp:
          host: smtp.exmail.qq.com
          auth: true
          port: 465
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory
            fallback: false

3.实现JavaMailSender类,继承JavaMailSenderImpl方法,重写部分功能

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;

/**
 * 实现多账号,轮询发送
 */
@Configuration
@EnableConfigurationProperties(MailProperties.class)
public class MyJavaMailSender extends JavaMailSenderImpl implements JavaMailSender {

    private static Logger logger = LoggerFactory.getLogger(MyJavaMailSender.class);

    private ArrayList<String> usernameList;
    private ArrayList<String> passwordList;
    private int currentMailId = 0;
    private int currentMailId2 = 0;

    private final MailProperties properties;

    public MyJavaMailSender(MailProperties properties) {
        this.properties = properties;

        // 初始化账号
        if (usernameList == null)
            usernameList = new ArrayList<String>();
        String[] userNames = this.properties.getUsername().split(",");
        if (userNames != null) {
            for (String user : userNames) {
                usernameList.add(user);
            }
        }

        // 初始化密码
        if (passwordList == null)
            passwordList = new ArrayList<String>();
        String[] passwords = this.properties.getPassword().split(",");
        if (passwords != null) {
            for (String pw : passwords) {
                passwordList.add(pw);
            }
        }
    }

    @Override
    protected void doSend(MimeMessage[] mimeMessage, Object[] object) throws MailException {
        super.setUsername(usernameList.get(currentMailId));
        super.setPassword(passwordList.get(currentMailId));
        logger.info("正在使用邮箱账号:"+super.getUsername()+"发送邮件.............");
        currentMailId2 = (currentMailId == (usernameList.size()-1)? 0 : (currentMailId+1));

        // 设置编码和各种参数
//        super.setHost(this.properties.getHost());
        super.setDefaultEncoding(this.properties.getDefaultEncoding().name());
        super.setJavaMailProperties(asProperties(this.properties.getProperties()));
        try {
            super.doSend(mimeMessage, object);
        } catch (MailException e) {
            e.printStackTrace();
        } finally {
            currentMailId = currentMailId2;
        }
    }

    private Properties asProperties(Map<String, String> source) {
        Properties properties = new Properties();
        properties.putAll(source);
        return properties;
    }

    @Override
    public String getUsername() {
        return usernameList.get(currentMailId);
    }

    public int getCurrentMailId() {
        return currentMailId;
    }

    public int getCurrentMailId2() {
        return currentMailId2;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值