Java-RuoyI单应用发送邮件

本文详细描述了如何在Java应用程序中使用RuoyI框架发送邮件,包括参数验证、文件路径处理、邮件内容构造、以及使用SMTP协议通过网易邮箱服务器发送带附件的邮件给多个收件人和抄送人。
摘要由CSDN通过智能技术生成

Java-RuoyI单应用发送邮件

业务逻辑示例

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.domain.vo.SendVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

@Controller
@RequestMapping("/business/send")
@CrossOrigin
public class SendController {
    @PostMapping("/sendMail")
    @ResponseBody
    public AjaxResult send(@RequestBody SendVo sendVo) {
        System.out.println("开始");
        if (sendVo == null){
            return AjaxResult.error("参数为空");
        }
        if(sendVo.getDate() == null || sendVo.getDate().trim().length() == 0){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyyMMdd");
            sendVo.setDate(simpleDateFormat.format(new Date()));
        }
        List<String> pathList = new ArrayList<>();
        pathList = sendVo.getPathList();
        if(pathList == null || pathList.size() == 0) {
            String path1 = "堆存日报_" + sendVo.getDate() + ".xls";
            String path2 = "盘存报表_" + sendVo.getDate() + ".xls";
            String path3 = "报表" + sendVo.getDate() + ".xls";
            String path4 = "报表" + sendVo.getDate() + ".xls";
            String path5 = "在场反馈表" + sendVo.getDate() + ".xls";
            pathList.add(path1);
            pathList.add(path2);
            pathList.add(path3);
            pathList.add(path4);
            pathList.add(path5);
        }
        sendVo.setThemtext(sendVo.getDate()+"日报表");
        if(sendVo.getContent() == null || sendVo.getContent().trim().length() == 0){
            sendVo.setContent("请查阅附件内容。");
        }
        if(sendVo.getSendMail() == null || sendVo.getSendMail().trim().length() == 0){
            return AjaxResult.error("发件人参数为空");
        }
        if(sendVo.getSendMailPassword() == null || sendVo.getSendMailPassword().trim().length() == 0){
            return AjaxResult.error("发件人密码参数为空");
        }
        List<String> receiveMail1 = new ArrayList<>();
        List<String> receiveMail1List = new ArrayList<>();
        receiveMail1 = sendVo.getReceiveMail1();
        if(receiveMail1 == null || receiveMail1.size() == 0){
            return AjaxResult.error("收件人参数为空");
        }else{
            String str = receiveMail1.get(0);
            String[] strAry = null;
            if(str.contains(";")){
                strAry = str.split(";");
            }else{
                strAry = new String[1];
                strAry[0] = str;
            }
            for (int i = 0; i <strAry.length; i++) {
                receiveMail1List.add(strAry[i]);
            }
        }
        List<String> receiveMail2 = new ArrayList<>();
        List<String> receiveMail2List = new ArrayList<>();
        receiveMail2 = sendVo.getReceiveMail2();
        if(receiveMail2 != null && receiveMail2.size() == 0){
            String str = receiveMail1.get(0);
            String[] strAry = null;
            if(str.contains(";")){
                strAry = str.split(";");
            }else{
                strAry = new String[1];
                strAry[0] = str;
            }
            for (int i = 0; i <strAry.length; i++) {
                receiveMail2List.add(strAry[i]);
            }
        }

		//sendMail邮件发送方法
        boolean result = sendMail(pathList,sendVo.getThemtext(),sendVo.getContent(),sendVo.getSendMail(),sendVo.getSendMailPassword(),receiveMail1List,receiveMail2List);
        if(result){
            return AjaxResult.success("发送成功");
        }else{
            return AjaxResult.error("发送失败");
        }
    }

sendMail邮件发送方法

    /**
     *
     * @param pathList 文件路径(可多个)
     * @param themtext 主题
     * @param content 正文
     * @param sendMail 发送人邮箱
     * @param sendMailPassword 发送人邮箱密码
     * @param receiveMail1List 收件人(可多个)
     * @param receiveMail2List 抄送人(可多个)
     * @return
     */
    public static boolean sendMail(List<String> pathList, String themtext, String content, String sendMail, String sendMailPassword, List<String> receiveMail1List, List<String> receiveMail2List) {
        Transport transport = null;
        List<InputStream> inputStreamList = new ArrayList<>();

        try {
            System.setProperty("mail.mime.splitlongparameters", "false");
            Properties props = new Properties();
            // 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
            props.put("mail.smtp.host", "smtp.163.com");
            // 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
            props.put("mail.smtp.auth", "true");
            // 用刚刚设置好的props对象构建一个session
            Session session = Session.getDefaultInstance(props);
            // 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使
            // 用(你可以在控制台(console)上看到发送邮件的过程)
            session.setDebug(false);
            // 用session为参数定义消息对象
            MimeMessage message = new MimeMessage(session);
            // 加载发件人地址
            message.setFrom(new InternetAddress(sendMail));/*删除此段-发件邮箱*/
            // 加载收件人地址
            if(receiveMail1List!=null && receiveMail1List.size() > 0) {
                for (String mail:receiveMail1List) {
                    if(mail!=null && mail.trim().length() > 0){
                        message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));
                    }
                }
            }
            // 加载抄送人地址
            if(receiveMail2List!=null && receiveMail2List.size() > 0){
                for (String mail:receiveMail2List) {
                    if(mail!=null && mail.trim().length() > 0) {
                        message.addRecipient(Message.RecipientType.CC, new InternetAddress(mail));
                    }
                }
            }
            // 加载主题
            message.setSubject(themtext);
            // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
            Multipart multipart = new MimeMultipart();
            // 设置邮件的文本内容
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setText(content);
            multipart.addBodyPart(contentPart);

            for (String filePath:pathList) {
                if(filePath == null || filePath.trim().length() == 0){
                    continue;
                }
                // 创建File对象
                System.out.println("filePath=="+filePath);
                String path = "D:\\XMDAILYREP\\"+filePath;
                System.out.println("path=="+path);
                File file = new File(path);
                if (file.exists()) {
                    // 创建FileInputStream对象
                    FileInputStream fis = new FileInputStream(file);
                    // 将FileInputStream转换为InputStream
                    InputStream is = new FileInputStream(file);
                    // 添加附件
                    BodyPart messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(is, "application/msexcel");
                    // 添加附件的内容
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    // 添加附件的标题
                    // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                    messageBodyPart.setFileName(MimeUtility.encodeText(file.getName() + ".xls"));
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            // 将multipart对象放到message中
            message.setContent(multipart);
            // 保存邮件
            message.saveChanges();
            // 发送邮件
            transport = session.getTransport("smtp");
            // 连接服务器的邮箱,此处是使用的163邮箱的服务器域名,也可以是某个指定的邮件服务器IP地址
            transport.connect("smtp.163.com", sendMail/*删除此段-发件人名称*/, sendMailPassword/*删除此段-发件人邮箱密码*/);
            // 把邮件发送出去
            transport.sendMessage(message, message.getAllRecipients());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                transport.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值