跳转至

Spring Cloud Alibaba

适用于基于 Spring Boot 3.5.x 的 Spring Cloud Alibaba 微服务的分步指南。Mailexam 通过 spring-boot-starter-mailJavaMailSender 接入 — 与 Spring Boot 相同的 SMTP 栈,运行在 Spring Cloud Alibaba 服务内。

所需条件

  • Mailexam 账户及带 SMTP 凭据的项目
  • JDK 17+ 与 Spring Cloud Alibaba 项目(Gradle 或 Maven)。

欢迎邮件(或控制台)复制以下信息:

  • YOUR_LOGIN — SMTP 登录名(例如 xxxxx);
  • YOUR_PASSWORD — SMTP 密码(与登录名配对);
  • 主机 — YOUR_LOGIN.mailexam.cn与登录名一致)。

1. 依赖

添加 Spring Cloud 与 Spring Cloud Alibaba BOM,然后引入 mail 及(可选)Nacos discovery。

Gradle(build.gradle):

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.5.0'
    id 'io.spring.dependency-management' version '1.1.7'
}

ext {
    set('springCloudVersion', '2025.0.0')
    set('springCloudAlibabaVersion', '2025.0.0.0')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
        mavenBom "com.alibaba.cloud:spring-cloud-alibaba-dependencies:${springCloudAlibabaVersion}"
    }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery'
}

Maven — 导入相同 BOM 并添加三个 starter。

SMTP 测试可不启用 Nacos

示例包含 Nacos discovery 以符合 Spring Cloud Alibaba 常见结构,但本地可将其关闭(见第 3 节),无需 Nacos 即可测试邮件。

2. 环境变量

本地开发使用 .env(勿提交密码)或在 Run Configuration / CI 中设置变量:

MAILEXAM_LOGIN=YOUR_LOGIN
MAILEXAM_PASSWORD=YOUR_PASSWORD
MAILEXAM_PORT=587
MAIL_FROM=noreply@example.test
NACOS_DISCOVERY_ENABLED=false
NACOS_SERVER_ADDR=127.0.0.1:8848

配置中的 SMTP 主机:${MAILEXAM_LOGIN}.mailexam.cn

发件人地址

MAIL_FROM 可以是任意测试地址 — 邮件会进入 Mailexam,而非真实收件人。

备选端口

MAILEXAM_PORT=587

spring.mail.properties.mail.smtp.starttls.enable=true

MAILEXAM_PORT=2525

与 587 相同,启用 STARTTLS。

MAILEXAM_PORT=25
spring.mail.properties.mail.smtp.starttls.enable=false

3. 应用配置

在主类上启用 discovery:

@SpringBootApplication
@EnableDiscoveryClient
public class MailServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(MailServiceApplication.class, args);
    }
}

src/main/resources/application.yml

spring:
  application:
    name: mail-service
  cloud:
    nacos:
      discovery:
        enabled: ${NACOS_DISCOVERY_ENABLED:false}
        server-addr: ${NACOS_SERVER_ADDR:127.0.0.1:8848}
  mail:
    host: ${MAILEXAM_LOGIN}.mailexam.cn
    port: ${MAILEXAM_PORT:587}
    username: ${MAILEXAM_LOGIN}
    password: ${MAILEXAM_PASSWORD}
    properties:
      mail.smtp.auth: true
      mail.smtp.starttls.enable: true

mail:
  from: ${MAIL_FROM:noreply@example.test}

端口 25 时需设置 mail.smtp.starttls.enable=false(见上表)。

4. 发送服务

package com.example.demo.mail;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class MailService {

    private final JavaMailSender mailSender;
    private final String from;

    public MailService(JavaMailSender mailSender, @Value("${mail.from}") String from) {
        this.mailSender = mailSender;
        this.from = from;
    }

    public void sendTest(String to, String subject, String body) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(body, false);
        mailSender.send(message);
    }
}

5. REST 端点

package com.example.demo.web;

import com.example.demo.mail.MailService;
import jakarta.mail.MessagingException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class MailController {

    private final MailService mailService;

    public MailController(MailService mailService) {
        this.mailService = mailService;
    }

    public record SendRequest(String to, String subject, String body) {
        public SendRequest {
            if (to == null || to.isBlank()) {
                to = "user@example.test";
            }
            if (subject == null || subject.isBlank()) {
                subject = "Spring Cloud Alibaba + Mailexam";
            }
            if (body == null || body.isBlank()) {
                body = "Mailexam test from Spring Cloud Alibaba";
            }
        }
    }

    @PostMapping("/mail/test")
    public Map<String, String> sendTest(@RequestBody SendRequest request) throws MessagingException {
        mailService.sendTest(request.to(), request.subject(), request.body());
        return Map.of("status", "ok");
    }
}

启动并验证:

./gradlew bootRun
curl -X POST http://127.0.0.1:8080/mail/test \
  -H 'Content-Type: application/json' \
  -d '{"to":"user@example.test","subject":"Test","body":"Hello"}'

邮件将出现在 Mailexam 控制台 → 您的项目 → 收件箱。

6. 本地开发与 CI

环境 建议
local IDE 或 .env 中的变量;无 Nacos 时保持 NACOS_DISCOVERY_ENABLED=false
CI 在 pipeline 变量中设置 MAILEXAM_LOGINMAILEXAM_PASSWORD

GitLab CI 示例:

variables:
  MAILEXAM_LOGIN: $MAILEXAM_LOGIN
  MAILEXAM_PASSWORD: $MAILEXAM_PASSWORD
  MAILEXAM_PORT: "587"
  MAIL_FROM: "noreply@example.test"
  NACOS_DISCOVERY_ENABLED: "false"

集成测试发送邮件后,通过 Mailexam API 验证投递。

7. 常见问题

TLS 或连接错误

  • spring.mail.host 必须为 {login}.mailexam.cnusername 为邮件中的同一登录名。
  • 登录名与密码为同一项目的配对凭据

启动时 Nacos 连接错误

  • 本地 SMTP 测试请设置 NACOS_DISCOVERY_ENABLED=false
  • 启用 discovery 时,确保 Nacos 在 NACOS_SERVER_ADDR 可达。

变量未替换

  • 运行应用前设置 MAILEXAM_LOGINMAILEXAM_PASSWORD;在 IDE 的 Run 配置中检查 Environment。

控制台中看不到邮件

  • 查看同一 Mailexam 项目的收件箱。
  • 启用日志:logging.level.org.springframework.mail=DEBUG

参见