user851316
user851316

Reputation: 29

PowerShell - sending mail script throwing error

Here is the Powershell Script code i am using

$SmtpClient = New-Object system.net.mail.smtpClient;
$mailmessage = New-Object system.net.mail.mailmessage;
$SmtpClient.Host = "exchange server name";
$SmtpClient.Credentials = New-Object System.Net.NetworkCredential("User name", "password");
$mailmessage.from = ("[email protected]");
$mailmessage.To.add("[email protected]");
$mailmessage.Subject = “Message”;
$mailmessage.Body = “Body”;
$smtpclient.Send($mailmessage);

Here is the error i am getting

Exception calling "Send" with "1" argument(s): "Failure sending mail." At C:\Users\user1\Desktop\sendmailPS.ps1:9 char:17 + $smtpclient.Send <<<< ($mailmessage); + CategoryInfo : NotSpecified: (:) [], MethodInvocationExcept ion + FullyQualifiedErrorId : DotNetMethodException

Any Help is appreciated and thanks in advance

Upvotes: 0

Views: 4110

Answers (1)

alroc
alroc

Reputation: 28174

Unless you have a need to maintain compatibility with PowerShell 1.0, use send-mailmessage instead. Linebreaks added for readability.

send-mailmessage -smtphost your.smtp.host -from [email protected] -to [email protected] `
-subject "message" -body "body" `
-Credential (New-Object -TypeName System.Management.Automation.PSCredential`
     -ArgumentList "user name" (ConvertTo-SecureString -String "password" -AsPlainText -Force))

Upvotes: 2

Related Questions