Java 发邮件支持移动邮箱/163/qq

项目中遇到的一个发送邮件的一个需求,特此记录一下!其中mailUserName是邮箱名称,mailPassword是开启pop3/smtp时的验证码

package com.ruoyi.common.utils;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;

@Slf4j
public class EmailUtils {


    /**
     * 发送邮件
     *
     * @param emailSubject  邮件主题
     * @param emailContent  邮件内容
     * @param addresseeList 邮件收件人地址List
     */
    public static void mailSend(String emailSubject, String emailContent, List<String> addresseeList) {
        //发件人邮箱 支持 139(移动)、163、qq
        String mailUserName = RuoYiConfig.getMailUserName();
        //开启pop3/smtp时的验证码
        String mailPassword = RuoYiConfig.getMailPassword();
        if (StringUtils.isEmpty(mailPassword) || StringUtils.isEmpty(mailUserName)) {
            throw new ServiceException("没有配置邮箱或邮箱smtp验证码!");
        }
        String smtpHost = "";
        if (mailUserName.contains("139")) {//移动 SMTP服务器
            smtpHost = "smtp.139.com";
        } else if (mailUserName.contains("qq")) {//腾讯 SMTP服务器
            smtpHost = "smtp.qq.com";
        } else if (mailUserName.contains("163")) {//网易 SMTP服务器
            smtpHost = "smtp.163.com";
        } else {
            throw new ServiceException("没有适配SMTP服务器,请重新填写发件人邮箱:只支持 139(移动)、163、qq 邮箱!");
        }
        // 配置邮件服务器
        Properties props = new Properties();

        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "25");
        // 创建Session对象
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailUserName, mailPassword);
            }
        });

        try {
            // 创建Message对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(mailUserName));
            for (int i = 0; i < addresseeList.size(); i++) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(addresseeList.get(i)));
            }
            message.setSubject(emailSubject);
            message.setText(emailContent);
            // 发送邮件
            Transport.send(message);
            log.info("发送邮件成功:已向" + addresseeList + "发送邮件");
        } catch (MessagingException e) {
            log.error("发送邮件失败:" + e.getMessage());
        }
    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值