M.Alcorn
M.Alcorn

Reputation: 21

Powershell to send mail

Error

New-Object : Cannot find an overload for "PSCredential" and the argument count: "2". At D:\Scripts\gsend.ps1:12 char:15

Code

#Create Password File (Only need once)
#$Credential = Get-Credential
#$Credential.Password | ConvertFrom-SecureString | Set-Content "D:\scripts\gsendcred.txt" 

#Send Email

$EncryptedCredential = "D:\scripts\gsendcred.txt"

$EmailUsername = "[email protected]"

$EncryptedPW = Get-Content "D:\scripts\gsendcred.txt"

$EncryptedCredential = ConvertTo-SecureString -String $EncryptedCredential -
AsPlainText -Force

$Credential = New-Object Management.Automation.PSCredential ($EmailUsername, 
$EncryptedPW)

$EmailFrom = "[email protected]"

$EmailTo = "[email protected]"

$EmailSubject = "GSEND Test Subject"

$EmailBody = "Test Body"

$SMTPServer = "smtp.gmail.com"

$SMTPPort = 587

$SMTPSsl = $true

Upvotes: 0

Views: 1498

Answers (2)

John Donnelly
John Donnelly

Reputation: 917

I believe your issue is handling credentials. Here is how I handle the smtp credentials:

$smtpPwd = "password"
$smtpCredentialsUsername = "[email protected]"
$smtpCredentialsPassword = ConvertTo-SecureString -String $smtpPwd -AsPlainText -Force

 $Credentials = New-Object –TypeName System.Management.Automation.PSCredential 
    –ArgumentList $smtpCredentialsUsername, $smtpCredentialsPassword

Then:

  $smtp.Credentials = $Credentials

Or if you are using Send-MailMessage store your email credentials locally by running this short script by itself beforehand:

Get-Credential | Export-Clixml C:\fso\myemailcreds.xml

It will prompt you to enter your credentials and then store them locally in (in this case) a folder called fso. Then in any Send-MailMessage cmdlet use the locally stored credentials as follows:

Send-MailMessage -To 'Recipient <[email protected]>' -from 'John Donnelly <[email protected]>' 
    -cc 'whoever <[email protected]>' -Subject $subject -Body $body 
    -BodyAsHtml -smtpserver "smtp.office365.com" -usessl 
    -Credential (Import-Clixml C:\fso\myemailcreds.xml) -Port 587

Upvotes: 1

Deepesh
Deepesh

Reputation: 610

You Can use below Powershell script for send mail

Send-MailMessage -To "[email protected]" -From "[email protected]" -Cc "[email protected]","[email protected]" -Subject Test Mail -BodyAsHtml $htmlbody -SmtpServer "mailhost.abc.com"

where $htmlbody is string variable that contain html.

Upvotes: 0

Related Questions