java实现邮件的群发及附件的发送

MultipartFile是springMVC封装的一种存储文件的方法,这里实现的是接口调用该方法可以直接将文件和正文等内容进行发送

import org.springframework.web.multipart.MultipartFile;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 发邮件工具类
 */
public final class MailUtils {
    private static final String USER = "***@**.com"; // 发件人称号,同邮箱地址
    private static final String PASSWORD = "***"; // 如果是qq邮箱可以使户端授权码,或者登录密码

    /**
     *
     * @param to 收件人邮箱
     * @param text 邮件正文
     * @param title 标题
     * @param files 附件
     */
    /* 发送验证信息的邮件 */
    public static boolean sendMail(String to, String text, String title, List<MultipartFile> files){
        try {
            final Properties props = new Properties();
            // 是否需要用户认证
            props.put("mail.smtp.auth", "true");
            // SMTP主机名
            props.put("mail.smtp.host", "smtp.qq.com");
            // 主机端口号
            props.put("mail.smtp.port", "xxx"); 
            // 启用TLS加密
            props.put("mail.smtp.starttls.enable", "false");
            
            // 构建授权信息,用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USER, PASSWORD);
                }
            };
            // 使用环境属性和授权信息,创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            //设置为debug模式,可以查看详细的发送log
            session.setDebug(true); 
            
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            message.setFrom(form);
			//xxx@qq.com;xxx@qq.com;xxx@qq.com
            String[] tos = to.split(";");
            //发件人
	        message.setFrom(new InternetAddress("xxx@qq.com"));
	        // 收件人
	        InternetAddress[] addresses = new InternetAddress[tos.length];
	        for (int i = 0; i < tos.length; i++) {
	            addresses[i] = new InternetAddress(tos[i]);
	        }
	        message.setRecipients(Message.RecipientType.TO, addresses);

            // 邮件主题
	        message.setSubject(title, "UTF-8");
	        //向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
	        MimeMultipart multipart = new MimeMultipart();
	        //设置邮件的文本内容
	        MimeBodyPart contentPart = new MimeBodyPart();
	        contentPart.setContent(text, "text/html;charset=UTF-8");
	        multipart.addBodyPart(contentPart);
	
	        //添加附件
	        for (MultipartFile multipartFile : files){
	            MimeBodyPart filePart = new MimeBodyPart();
	            File file = MultipartFileToFile(multipartFile);
	            DataSource source = new FileDataSource(file);
	            //添加附件的内容
	            filePart.setDataHandler(new DataHandler(source));
	            //添加附件的标题
	            filePart.setFileName(MimeUtility.encodeText(Objects.requireNonNull(multipartFile.getOriginalFilename())));
	            multipart.addBodyPart(filePart);
	        }
	
	        //将multipart对象放到message中
	        message.setContent(multipart);
	        //设置显示的发件时间
	        message.setSentDate(new Date());
	        //保存前面的设置
	        message.saveChanges();
	        //发送邮件到所有的收件地址
	        Transport.send(message, message.getAllRecipients());
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
	//将MultipartFile转换为File
	public static File MultipartFileToFile(MultipartFile multiFile) {
	    // 获取文件名
	    String fileName = multiFile.getOriginalFilename();
	    if (fileName == null){
	        return null;
	    }
	    // 获取文件后缀
	    String prefix = fileName.substring(fileName.lastIndexOf("."));
	    // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
	    try {
	        File file = File.createTempFile(fileName, prefix);
	        multiFile.transferTo(file);
	        return file;
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return null;
	}
}

以上便是大致的代码,测试是否运行的话,可以在本地进行调试

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

?abc!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值