阿里企业邮箱授权码怎么获取以及测试发送关键代码

  • 背景
    公司需求需要设置邮箱发送,需要注册一个企业邮箱,发现阿里云邮箱配置授权码有些坑,记录一下

  • 开始

  1. 首先我们注册完企业邮箱,postmaster开头的管理员账号,其中这个是不能开启SMTP 服务,需要开通注册一个员工账号才可以,不过主体postmaster账号需要设置一些东西才行

在这里插入图片描述

  1. 登录员工账号开通授权码

在这里插入图片描述

在这里插入图片描述

到这里就是完成了配置授权码关键部分

  • 代码部分
  1. 导入依赖分别是pom.xml和gradle,根据不同的项目导入即可
    pom.xml
<!-- JavaMail 核心依赖 -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>
<!-- 简化配置的工具类(可选) -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

build.gradle

plugins {
    id 'java'
}

repositories {
    mavenCentral() // 必须配置中央仓库,拉取邮件依赖
}

dependencies {
    // JavaMail 核心依赖(兼容Java 8+)
    implementation 'javax.mail:javax.mail-api:1.6.2'
    implementation 'com.sun.mail:javax.mail:1.6.2'
    
    // 可选:简化字符串/日期处理(示例中用到)
    implementation 'org.apache.commons:commons-lang3:3.14.0'
    
    // 测试依赖(可选)
    testImplementation 'junit:junit:4.13.2'
}

// 可选:指定Java版本(根据你的项目调整)
java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}
  1. 测试逻辑代码


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

/**
 * Gradle项目 - 邮箱阈值提醒工具类
 */
public class EmailThresholdAlert {

    // ========== 请修改为你的实际配置 ==========
    private static final String SMTP_HOST = "smtp.qiye.aliyun.com"; // QQ邮箱填smtp.qq.com
    private static final String SMTP_PORT = "465"; // SSL端口,无需修改
    private static final String SENDER_EMAIL = "企业邮箱地址"; // 发送方邮箱
    private static final String SENDER_PASSWORD = "授权码"; // 邮箱授权码(非登录密码)
    private static final String RECEIVER_EMAIL = "接收方的邮箱"; // 接收方邮箱(多个用逗号分隔)
    // =========================================

    /**
     * 发送阈值提醒邮件
     */
    public static void sendAlertEmail(String subject, String content) throws MessagingException {
        // 1. 配置SMTP参数
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        // 2. 邮箱认证
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SENDER_EMAIL, SENDER_PASSWORD);
            }
        };

        // 3. 创建邮件会话
        Session session = Session.getInstance(props, auth);
        session.setDebug(false); // 生产环境关闭调试

        // 4. 构建邮件
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(SENDER_EMAIL));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECEIVER_EMAIL));
        message.setSubject(subject, "UTF-8"); // 解决中文乱码
        message.setContent(content, "text/html;charset=UTF-8"); // 支持HTML格式
        message.saveChanges();

        // 5. 发送邮件
        Transport.send(message);
        System.out.println("阈值提醒邮件发送成功!");
    }

    /**
     * 阈值判断核心逻辑
     * @param currentValue 当前监控值(如CPU负载、库存、订单量)
     * @param threshold 触发阈值
     * @param monitorName 监控项名称
     */
    public static void checkThresholdAndAlert(double currentValue, double threshold, String monitorName) {
        if (currentValue > threshold) { // 可修改判断逻辑:> / < / >= / <=
            // 构建告警邮件内容
            String subject = String.format("[告警] %s 超过阈值", monitorName);
            String content = String.format(
                    "<html>" +
                            "<body>" +
                            "<h3>监控项:%s</h3>" +
                            "<p>当前值:<font color='red'>%.2f</font></p>" +
                            "<p>阈值:%.2f</p>" +
                            "<p>触发时间:%s</p>" +
                            "</body>" +
                            "</html>",
                    monitorName, currentValue, threshold, java.time.LocalDateTime.now()
            );

            // 异步发送邮件(避免阻塞主流程,Gradle项目通用)
            new Thread(() -> {
                try {
                    sendAlertEmail(subject, content);
                } catch (MessagingException e) {
                    System.err.println("邮件发送失败:" + e.getMessage());
                    e.printStackTrace();
                }
            }).start();
        } else {
            System.out.printf("%s 当前值%.2f未超过阈值%.2f,无需提醒%n", monitorName, currentValue, threshold);
        }
    }

    // 测试入口
    public static void main(String[] args) {
        // 示例1:CPU负载阈值80,当前85 → 触发告警
        checkThresholdAndAlert(85.5, 80.0, "系统CPU负载");
        // 示例2:库存阈值100,当前90 → 不触发
        checkThresholdAndAlert(90, 100.0, "商品A库存");
    }
}

邮箱参考

邮箱类型SMTP 服务器端口(SSL)
163 邮箱smtp.163.com465
QQ 邮箱smtp.qq.com465
Gmailsmtp.gmail.com465
阿里邮箱smtp.qiye.aliyun.com465

效果这样
在这里插入图片描述

到这里差不多就结束了,如果发现博文有问题,欢迎指点一二,欢迎打赏
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Hello Bug

谢谢老板,老板大气,老板硬邦邦

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

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

打赏作者

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

抵扣说明:

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

余额充值