因微软改动SMTP失效,如何用Java Selenium+Token授权自动化Outlook?
Java + Selenium 结合 Token 授权实现 Outlook 自动化方案
由于组织内已停用SmtpClientAuthentication,导致SMTP端口认证失败(报错535 5.7.139),以下是基于Java+Selenium+OAuth2 Token的替代自动化方案,通过操控Outlook网页版完成邮件操作。
核心思路
通过OAuth2协议获取Outlook API授权Token,结合Selenium操控网页版Outlook,实现无SMTP依赖的邮件自动化(发件、收件、草稿管理等)。
分步实现
1. 注册Azure AD应用获取OAuth凭证
- 登录Azure门户,创建一个"桌面应用"类型的AD应用
- 配置重定向URI为
https://login.microsoftonline.com/common/oauth2/nativeclient - 添加委派权限:
Mail.ReadWrite、User.Read、openid、profile,组织账号需提交管理员同意 - 记录应用的
客户端ID(Client ID)和租户ID(Tenant ID)
2. 用MSAL4J获取Access Token
使用微软官方的MSAL4J库实现Token获取,首次运行会弹出登录窗口完成认证,后续可通过刷新Token自动续期:
import com.microsoft.aad.msal4j.*; import java.util.Collections; import java.util.concurrent.CompletableFuture; public class OutlookTokenHelper { private static final String CLIENT_ID = "你的客户端ID"; private static final String TENANT_ID = "你的租户ID"; private static final String[] REQUIRED_SCOPES = {"https://outlook.office.com/Mail.ReadWrite", "openid"}; public static String getValidAccessToken() throws Exception { PublicClientApplication pca = PublicClientApplication.builder(CLIENT_ID) .authority("https://login.microsoftonline.com/" + TENANT_ID) .build(); CompletableFuture<IAuthenticationResult> authResultFuture = pca.acquireToken( InteractiveRequestParameters.builder(new java.net.URI("https://login.microsoftonline.com/common/oauth2/nativeclient")) .scopes(Collections.singletonList(REQUIRED_SCOPES[0])) .build() ); return authResultFuture.get().accessToken(); } }
3. Selenium操控Outlook网页版
复用浏览器配置保存登录状态,避免每次运行都重新登录,然后执行自动化操作:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class OutlookWebAutomation { public static void main(String[] args) throws Exception { // 配置Chrome浏览器,复用用户配置保存登录状态 ChromeOptions options = new ChromeOptions(); options.addArguments("--user-data-dir=./outlook-chrome-profile"); // 本地保存用户目录 options.addArguments("--start-maximized"); WebDriver driver = new ChromeDriver(options); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15)); // 获取Token(首次运行需手动完成一次登录) OutlookTokenHelper.getValidAccessToken(); // 打开Outlook网页版 driver.get("https://outlook.office.com/mail/"); // 等待页面加载完成,点击新建邮件 wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='新建邮件']"))).click(); // 填写收件人、主题、正文 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@aria-label='收件人']"))).sendKeys("target@example.com"); driver.findElement(By.xpath("//input[@aria-label='主题']")).sendKeys("自动化测试邮件"); driver.findElement(By.xpath("//div[@aria-label='邮件正文']")).sendKeys("此邮件由Java+Selenium自动化脚本发送。"); // 发送邮件 wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@aria-label='发送']"))).click(); // 验证发送完成后关闭浏览器 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(), '邮件已发送')]"))); driver.quit(); } }
4. 依赖与环境配置
在pom.xml中添加必要依赖:
<dependencies> <!-- MSAL4J用于OAuth2认证 --> <dependency> <groupId>com.microsoft.azure</groupId> <artifactId>msal4j</artifactId> <version>1.23.0</version> </dependency> <!-- Selenium核心与Chrome驱动 --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.15.0</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-chrome-driver</artifactId> <version>4.15.0</version> </dependency> </dependencies>
- 确保ChromeDriver版本与本地Chrome浏览器版本一致,下载对应版本驱动即可
- 首次运行脚本时,会弹出微软登录窗口,登录组织邮箱完成授权后,后续运行将自动复用登录状态
关键注意事项
- 组织账号需管理员提前同意Azure应用的权限,否则会出现权限不足报错
- Outlook网页版的DOM结构可能随版本更新变化,需定期检查并调整元素定位表达式
- 若需长时间运行,可通过MSAL4J的刷新Token机制自动获取新的Access Token,无需重复登录
内容的提问来源于stack exchange,提问作者Manikantan
相关产品推荐
相关产品推荐

