PowerShell通过SMTP发送20-50MB大附件时遇连接强制关闭错误
问题描述
尝试使用PowerShell发送带有20-50MB压缩附件的邮件时,使用Send-MailMessage cmdlet遇到如下错误:
Send-MailMessage : Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
执行的代码如下:
$from = "murat@abc.com" $to = "azamat@abc.com" $subject = "Report is attached. Please take a look!" $body = "This is a report email " $attachment = "report.txt" $encoding = [System.Text.Encoding]::UTF8 Send-MailMessage -From $from -To $to -Subject $subject -Body $body -Encoding $encoding -Attachments $attachment -SmtpServer "smtp.abc.com"
怀疑问题与大附件大小有关,但不确定如何处理,想知道能否通过PowerShell正常向SMTP服务器发送大附件?
解决办法
1. 先确认SMTP服务器的附件限制
大部分SMTP服务器默认会限制附件大小(比如常见的是25MB),先联系邮件服务提供商或者检查SMTP服务器配置,确认允许的最大附件尺寸。如果你的附件超过了限制,服务器会直接断开连接,就会出现你遇到的错误。
2. 自定义SMTP客户端配置(替代Send-MailMessage)
Send-MailMessage底层依赖.NET的SmtpClient,但默认参数不够灵活。可以直接调用.NET类来设置更长的超时时间,以及启用SSL(如果服务器要求):
$from = "murat@abc.com" $to = "azamat@abc.com" $subject = "Report is attached. Please take a look!" $body = "This is a report email " $attachmentPath = "report.txt" $smtpServer = "smtp.abc.com" # 创建SMTP客户端实例 $smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer) $smtpClient.Timeout = 300000 # 设置超时为5分钟(300000毫秒) $smtpClient.EnableSsl = $true # 如果服务器要求SSL加密,取消注释此行 $smtpClient.Credentials = New-Object System.Net.NetworkCredential("你的用户名", "你的密码") # 若需认证,添加此行 # 创建邮件对象 $mailMessage = New-Object System.Net.Mail.MailMessage $mailMessage.From = $from $mailMessage.To.Add($to) $mailMessage.Subject = $subject $mailMessage.Body = $body $mailMessage.BodyEncoding = [System.Text.Encoding]::UTF8 $mailMessage.Attachments.Add((New-Object System.Net.Mail.Attachment($attachmentPath))) try { $smtpClient.Send($mailMessage) Write-Host "邮件发送成功" } catch { Write-Host "发送失败:$($_.Exception.Message)" } finally { # 释放资源 $mailMessage.Dispose() $smtpClient.Dispose() }
3. 分卷压缩附件
如果SMTP服务器的大小限制无法调整,把大压缩包拆分成多个小文件(比如每个20MB以内),可以用7-Zip等工具创建分卷压缩包,然后将所有分卷作为附件发送,收件人解压时会自动合并。
4. 改用邮件服务商API发送
如果SMTP方式始终受限,可考虑使用邮件服务商提供的REST API(如Exchange Graph API),这类API通常支持更大的附件上传,不过需要提前配置API权限和认证信息。
内容的提问来源于stack exchange,提问作者Murat Ishenbaev
相关产品推荐
相关产品推荐

