首页 > 解决方案 > 隐式 SMTP 替代方案

问题描述

为了使用 powershell 使用隐式 SMTP 服务器,我尝试了以下脚本,但它不起作用(例外:传输到服务器故障)

请对使用 Powershell 使用隐式 SMTP 的另一种方法有任何评论或想法吗?

# Mail Message
$from = "user@domain.com"
$to = "user@domain.com"
$subject = "Hello from PowerShell"
$body = "This is a message saying hello from PowerShell."
$hasAttachment = $false
$attachmentPath = "attachmentPath.txt"

# Mail Server Settings
$server = "x.x.x.x"
$serverPort = 465
$timeout = 30000          # timeout in milliseconds
$enableSSL = $true
$implicitSSL = $true

# Get user credentials if required
if ($enableSSL)
{
    #$credentials = [Net.NetworkCredential](Get-Credential)
}

if (!$enableSSL -or !$implicitSSL)
{
  # nothing  
}
else
{
    # Load System.Web assembly
    [System.Reflection.Assembly]::LoadWithPartialName("System.Web") > $null    
    # Create a new mail with the appropriate server settigns
    $mail = New-Object System.Web.Mail.MailMessage
    $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", $server)
    $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", $serverPort)
    $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", $true)
    #$mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", $credentials.UserName)
    #$mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", $credentials.Password)
    $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout", $timeout / 1000)
    # Use network SMTP server...
    $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2)
    # ... and basic authentication
   # $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 0)

    # Set up the mail message fields
    $mail.From = $from
    $mail.To = $to
    $mail.Subject = $subject
    $mail.Body = $body

    # Send the message
    Write-Output "Sending email to $to..."
    try
    {
        [System.Web.Mail.SmtpMail]::Send($mail)
        Write-Output "Message sent."
    }
    catch
    {
        Write-Error $_
        Write-Output "Message send failed."
    }
}

PS:我不能使用 System.Net.Mail.MailMessage 对象,因为 .Net (Powershell) 不支持隐式 SMTP

标签: powershellsmtp

解决方案


推荐阅读