Nodemailer配置Office365 SMTP无法发送邮件问题咨询
Nodemailer 连接Office365 SMTP发信失败解决方案
问题背景
使用Nodemailer对接Office365 SMTP服务发信失败,初始配置如下:
var transporter = nodemailer.createTransport({ host: 'smtp.office365.com', port: '587', auth: { user: 'user@domain.com', pass: 'userpassword', }, });
尝试调整过secureConnection、端口、TLS加密套件等参数仍未解决,测试过的配置片段如下:
secureConnection: false, port: 587, tls: { ciphers:'SSLv3' }
已在Office365后台配置好应用专用密码,同账号同SMTP参数下,使用以下Python代码可以正常发送邮件:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText username = "user@domain.com" password = "userpassword" mail_from = "email@email.com" mail_to = "email@email.com" mail_subject = "Test Subject" mail_body = "This is a test message" mimemsg = MIMEMultipart() mimemsg['From']=mail_from mimemsg['To']=mail_to mimemsg['Subject']=mail_subject mimemsg.attach(MIMEText(mail_body, 'plain')) connection = smtplib.SMTP(host='smtp.office365.com', port=587) connection.starttls() connection.login(username,password) connection.send_message(mimemsg) connection.quit()
故障原因
配置存在4个核心问题:
port参数传入了字符串格式的'587',Nodemailer要求端口参数必须为数字类型,字符串格式会导致连接逻辑异常- 错误指定TLS加密套件为
SSLv3,微软Office365早已全面禁用SSLv3、TLS1.0、TLS1.1等不安全协议,目前最低要求TLS 1.2版本,指定SSLv3会直接被服务端拒绝连接 - 没有显式配置STARTTLS相关参数,和Python代码里显式调用
starttls()的逻辑不匹配,导致加密流程不符合Office365的连接要求 - 使用了已废弃的
secureConnection参数,新版Nodemailer中该参数不会生效,无法控制TLS连接模式
可用配置
替换为以下配置即可正常发信:
const transporter = nodemailer.createTransport({ host: 'smtp.office365.com', port: 587, // 必须传数字类型,不要加引号 secure: false, // 587端口为STARTTLS模式,必须设为false;465隐式TLS端口才设为true requireTLS: true, // 强制连接后启用TLS加密,对应Python代码中的starttls()调用 auth: { user: 'user@domain.com', // 后续sendMail时的from地址必须和这里完全一致 pass: '你配置的Office365应用专用密码' }, tls: { ciphers: 'TLSv1.2', minVersion: 'TLSv1.2' // 强制使用TLS1.2及以上版本,符合Office365的协议要求 } });
验证方式
配置完成后可以先调用verify方法测试连通性,确认连接正常后再执行发信逻辑:
transporter.verify((error, success) => { if (error) { console.log('SMTP连接失败:', error); return; } // 连接正常,执行发信 transporter.sendMail({ from: 'user@domain.com', // 必须和auth.user保持一致 to: 'target@xxx.com', subject: '测试邮件', text: '邮件内容' }, (err, info) => { if (err) console.log('发信失败:', err); else console.log('发信成功:', info); }) })
额外注意事项
- 不要给587端口设置
secure: true,该参数仅适用于465端口的隐式TLS连接,587端口设置为true会导致连接握手失败 - 如果账号开启了多因素认证(MFA),必须使用应用专用密码登录,不能使用账号的常规登录密码
- 发信时的
from地址必须和SMTP认证的账号邮箱完全一致,Office365会校验发件人身份,冒用其他发件人地址会被直接拦截
内容的提问来源于stack exchange,提问作者Pim
相关产品推荐
相关产品推荐

