我尝试使用默认值创建模块,如下所示:
function Send-Mail ($EmailTo = "all@example.com" , $Body = "Warning! Technical Maintance today", $Subject = "*** Warning! ***")
{
$EmailFrom = "it@example.com"
$SMTPServer = "mail.example.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("it", "Hjcnthv1");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
Export-ModuleMember -Function 'Send-Mail'
然后我试图使用它:
Import-Module '\\dc01\scripts$\_server\Send-Mail.psm1'
Send-Mail user@example.com "Text" "Subject"
但我收到错误:
Exception calling "Send" with "4" argument(s): "Failure sending mail."
At \\dc01\scripts$\_server\Send-Mail.psm1:14 char:1
+ $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
我做错了什么?
答案 0 :(得分:0)
您的模块创建很好,错误归结于您的功能无法正常工作。尝试在发送之前先创建消息对象。
$msg = New-object System.Net.Mail.MailMessage -ArgumentList @($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient.Send($msg)
您还选择启用SSL而不向SMTP客户端提供证书$SMTPClient.ClientCertificates
。在提供凭据时,您可能不需要SSL,因此您可以删除行$SMTPClient.EnableSsl = $true
。
在旁注中,您可以添加以下内容以在使用后处理您的对象。
$msg.Dispose()
$SMTPClient.Dispose()