PowerShell经Gmail SMTP发信报5.7.0认证错误的解决及附件添加咨询
PowerShell 5.1 Gmail SMTP发信故障修复与附件添加方案
故障根因说明
你碰到的5.7.0 Authentication Required报错,是Google调整个人Gmail服务策略直接导致的:
- 自2022年起,个人版Gmail全面关闭“低安全性应用直连SMTP”通道,哪怕手动在后台打开对应权限开关,服务端也会直接拒绝认证请求
- 个人Gmail账号要使用SMTP发信,必须先绑定两步验证,生成16位应用专用密码替代日常登录密码,否则认证100%失败
- Google Workspace(原G Suite)的企业账号,在默认安全配置合规的前提下,最初写的测试代码不需要改动就能正常发信
必做修复配置步骤
- 在个人Gmail账号的安全设置中完成两步验证绑定
- 在两步验证的配置模块中生成16位应用专用密码,替换脚本中原有的
$emailSmtpPass变量值,禁止使用日常登录邮箱的明文密码 - 当前使用的PowerShell 5.1版本,默认系统加密协议栈不包含TLS 1.2,而Gmail SMTP服务强制要求TLS 1.2以上加密通道完成握手,就算密码填对,也会因为加密版本不匹配连接失败,必须在脚本最开头追加强制启用TLS 1.2的代码:
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 - 核对SMTP参数配置:服务器地址为
smtp.gmail.com,587端口对应STARTTLS加密、465端口对应SSL加密,必须将$SMTPClient.EnableSsl设为$true,不可遗漏
邮件附件添加实现方法
给邮件加附件不需要改动原有SMTP客户端的任何配置,只需要在创建完邮件实例后,把本地文件加载为附件对象挂到邮件上即可,实战代码里最好提前加文件存在校验,避免路径错误直接让脚本崩溃:
# 定义需要附加的本地文件路径列表 $attachmentPaths = @( "C:\Reports\daily_output.pdf", "C:\Logs\script_run.log" ) # 循环校验并加载附件 foreach ($file in $attachmentPaths) { # 提前校验文件是否存在,避免路径错误触发异常 if (Test-Path -Path $file) { $mailAttachment = New-Object System.Net.Mail.Attachment($file) $emailMessage.Attachments.Add($mailAttachment) } }
整合后可直接运行的完整脚本
# 强制启用TLS 1.2适配Gmail SMTP要求 [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $emailSmtpServer = "smtp.gmail.com" $emailSmtpServerPort = "587" $emailSmtpUser = "你的Gmail地址@gmail.com" $emailSmtpPass = "你生成的16位应用专用密码" $emailMessage = New-Object System.Net.Mail.MailMessage $emailMessage.From = "你的Gmail地址@gmail.com" $emailMessage.To.Add("收件人地址@xxx.com") $emailMessage.Subject = "Small mail for a friend" $emailMessage.IsBodyHtml = $true $emailMessage.Body = @" <p><strong>Hello me</strong>.</p> <p>It seems to work</p> <p>JP</p> "@ # 加载附件逻辑 $attachmentPaths = @( "C:\Reports\daily_output.pdf", "C:\Logs\script_run.log" ) foreach ($file in $attachmentPaths) { if (Test-Path -Path $file) { $mailAttachment = New-Object System.Net.Mail.Attachment($file) $emailMessage.Attachments.Add($mailAttachment) } } $SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort ) $SMTPClient.EnableSsl = $true $SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass ); $SMTPClient.Send( $emailMessage )
内容的提问来源于stack exchange,提问作者Rituparno Bhattacharya
相关产品推荐
相关产品推荐

