Liferay对接Office365 SMTP发邮件出现AuthenticationFailedException排查
Liferay对接Office 365发送邮件AuthenticationFailedException故障排查方案
1. 开启SMTP详细调试日志获取具体错误
- 临时在执行的脚本中加入调试属性配置,重现场景即可拿到完整的SMTP交互日志:
def session = MailServiceUtil.getSession() def props = session.getProperties() // 开启全量调试日志 props.setProperty("mail.debug", "true") props.setProperty("mail.smtp.debug", "true") props.setProperty("mail.smtp.auth.debug", "true") MailServiceUtil.clearSession()
- 开启后日志会打印完整的和Office 365 SMTP服务的交互内容,包括服务端返回的具体认证失败原因,比如是TLS不支持、账号权限不足、发件人不匹配等。
2. 补全Office 365必需的SMTP配置项
Office 365 SMTP服务强制要求以下配置,你当前提供的配置项均缺失:
# 开启SMTP认证 mail.smtp.auth=true # 开启STARTTLS加密 mail.smtp.starttls.enable=true # 发件人地址必须和smtp.user完全一致,不允许自定义别名 mail.smtp.from=user@example.com
注意:你之前使用的密码更新脚本参数错误,
PropsKeys.MAIL_SESSION_MAIL不是密码对应的配置key,会导致密码配置根本没有写入正确位置,这是大概率的故障诱因,正确的全量配置脚本参考如下:
def session = MailServiceUtil.getSession() def props = session.getProperties() props.setProperty("mail.smtp.host", "smtp.office365.com") props.setProperty("mail.smtp.port", "587") props.setProperty("mail.smtp.user", "user@example.com") props.setProperty("mail.smtp.password", "你的实际密码") props.setProperty("mail.smtp.auth", "true") props.setProperty("mail.smtp.starttls.enable", "true") props.setProperty("mail.smtp.from", "user@example.com") MailServiceUtil.clearSession()
3. 验证配置实际生效状态
执行以下脚本打印所有生效的邮件配置,确认参数和预期一致:
def session = MailServiceUtil.getSession() def props = session.getProperties() props.each { key, value -> if (key.toString().startsWith("mail.smtp")) { println("${key} : ${value}") } }
重点检查密码、用户名、auth、starttls四个参数的取值是否正确,避免配置脚本执行后未生效的问题
4. 改造测试脚本捕获全量异常
原有测试脚本未做异常捕获,可能漏掉嵌套的底层异常,使用以下脚本测试:
import javax.mail.AuthenticationFailedException import com.liferay.mail.kernel.service.MailServiceUtil import com.liferay.mail.kernel.model.MailMessage import javax.mail.internet.InternetAddress try { def from = new InternetAddress("user@example.com", "user@example.com") def to = new InternetAddress ("other@example.com", "other@example.com") def mail = new MailMessage(from, to, "subject", "message", false) MailServiceUtil.sendEmail(mail) println("邮件发送成功") } catch (Exception e) { println("顶层异常:" + e.getMessage()) // 打印所有嵌套异常 Throwable cause = e.getCause() while (cause != null) { println("嵌套异常:" + cause.getMessage()) if (cause instanceof AuthenticationFailedException) { cause.printStackTrace() } cause = cause.getCause() } }
5. Office 365账号侧校验
- 如果账号开启了多因素认证(MFA),不能直接使用登录密码,需要在账号安全中心生成应用专用密码用于SMTP认证
- 联系Exchange管理员确认该账号已开启「SMTP提交」权限,未被限制使用SMTP服务
- 确认Liferay服务器出口IP未被Office 365加入限制列表,可在服务器上直接用openssl测试连通性:
openssl s_client -starttls smtp -connect smtp.office365.com:587
内容的提问来源于stack exchange,提问作者SamWM
相关产品推荐
相关产品推荐

