I am looking to improve an old batch script and upgrade it to powershell, this is a robocopy batch script and i would like it to send a mail with the logfile attatched when it is finished. i managed to get the drive mappings and robocopy part sorted but im having some issues getting the send-mailmessage part to work
`$SourceFolder = "V:\"
$DestinationFolder = "Y:\"
$Dateandtime = Get-Date -format filedate
$password = XXXXXXXXX
$Subject = "Robocopy Results: Backup USA - NL"
$SMTPServer = "mailserver.domain.com"
$Sender = "backupusr#domain.com"
$Username = "backupusr"
$Recipients = "administrator#domain.com"
$Admin = "administrator#domain.com"
$SendEmail = $True
$IncludeAdmin = $True
$AsAttachment = $False
$Cred = new-object Management.Automation.PSCredential $Username, ($password
| ConvertTo-SecureString -AsPlainText -Force)`
This is the line that causes the script to timeout
Send-MailMessage -SmtpServer $SMTPServer -From $Sender -To $Recipients -Subject $Subject -Body "Robocopy results are attached." -DeliveryNotificationOption onFailure -UseSsl -Credential $Cred
this is the error i recieve
Send-MailMessage : The operation has timed out.
At C:\Scripts\bpcti-robocopy.ps1:113 char:1
+ Send-MailMessage -SmtpServer $SMTPServer -From $Sender -To $Recipient ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
Any help would be greatly appreciated.
The -Credential parameter takes a PSCredential object. You can use Get-Credential to interactively create one using a username and password combination. More detail here.
Alternatively, as your password is already in plaintext in your script, you can use the process as described here and construct a new PSCredential.
# Convert the plaintext password into a secure string.
$SecurePassword = ConvertTo-SecureString "XXXXXXXXX" -AsPlainText -Force
# Create a new PSCredential using the username and secure string password.
$Cred = New-Object System.Management.Automation.PSCredential ("backupusr#domain.com", $SecurePassword)
Send-MailMessage -SmtpServer mailserver.domain.com -From backupusr#domain.com -To administrator#domain.com -Subject testing -Body "Robocopy results are attached." -DeliveryNotificationOption onFailure -Credential $Cred
Beware that the username should include the #domain.com.
Related
I want to send an email via powershell using function Send-MailMessage.
My smtp server requires UserName and Password.
I am passing it as parameters, however getting an error.
$CredUser = "123UserPass"
$CredPassword = "1234/5678/999"
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CredUser, $CredPassword
Send-MailMessage -SmtpServer "smtp.amazonaws.com" -Port 587 -Credential $Credential -UseSsl -From 'DBATeam#email.com' -To 'me#email.com' -Subject 'TEST'
Error message:
New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At line:3 char:16
+ ... redential = New-Object -TypeName System.Management.Automation.PSCrede ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Send-MailMessage : Cannot process argument transformation on parameter 'Credential'. userName
At line:4 char:90
+ ... tp.us-east-2.amazonaws.com" -Port 587 -Credential $Credential -UseSsl ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.PowerShell.Commands.SendMailMessage
I tried to use ConvertTo-SecureString -String "mypassword" but also getting a conversion error.
Try:
$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force
Provided you are using version 5.1 or later you can also use the ::new() static method in place o f New-Object (totally optional).
$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )
Send-MailMessage -SmtpServer "smtp.amazonaws.com" -Port 587 -Credential $Credential -UseSsl -From 'DBATeam#email.com' -To 'me#email.com' -Subject 'TEST'
You can incorporate splatting if you want to add some readability:
$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )
$SMTPParams = #{
SmtpServer = 'smtp.amazonaws.com'
Port = 587
Credential = $Credential
UseSsl = $true
From = 'DBATeam#email.com'
To = 'me#email.com'
Subject = 'TEST'
}
Send-MailMessage #SMTPParams
Note: some may frown on a password being visible. You can store the password securely in a file, then call it back for use. As long as it's by the same user on the same machine.
$SecurePassword = Read-Host -Prompt "Enter Password" -AsSecureString
$SecurePassword | ConvertFrom-SecureString | Out-File C:\temp\SecurePasswword.txt
$CredPassword = Get-Content C:\temp\SecurePasswword.txt | ConvertTo-SecureString
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )
Obviously you'll want to change the path to the file, so as not to advertise it. Establish the password file with the first 2 lines. Then use the second 2 in your current script to set up the creds for your SMTP command...
Documented here
I have prepared the PowerShell script for sending emails using SendGrid. But while converting plain text password of SendGrid account into secure string, then I am getting the following error:
“unable to convert type string to secure string”
Sample Script:
$SecurePassword = ConvertTo-SecureString "Demo123" -AsPlainText -Force
So, can anyone suggest me how to resolve this issue.
$Username ="Name#azure.com"
$Password = ConvertTo-SecureString "Demo123" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $Username, $Password
$SMTPServer = "smtp.sendgrid.net"
$EmailFrom = "from#mail.com"
$EmailTo = "to#mail.com"
$Subject = "SendGrid test"
$Body = "SendGrid testing successful"
Send-MailMessage -smtpServer $SMTPServer -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body
I am able to run same command in Powershell:
My Powershell Version is 5.7.0.18831.
I have written a small script that are using PSFTP to connect to a FTP server, download some files and conclude by sending an email with a summary of downloaded files.
I get a problem with the send-mailmessage part, which fails with this error:
Send-MailMessage : The remote certificate is invalid according to the validation procedure.
When running the send-mailmessage alone, it works flawlessly, it is only when using it combined with PSFTP, it fails. I am guessing, that it is the due to having made a session with the ftpserver, that somehow interferes, but that session should be ended when we come to the send mail. I can't figure this out, can anybody help?
My script:
#--------- FTP server variables here ------
$User = "XXX"
$Pass = "XXX"
$EncryptedPass = ConvertTo-SecureString -String $Pass -asPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User,$EncryptedPass)
$Server = "XXX"
#-------- Mail credentials here -----------
$User_ = "XXX"
$Pass_ = "XXX"
$EncryptedPass_ = ConvertTo-SecureString -String $Pass_ -asPlainText -Force
$Mailcredentials = New-Object System.Management.Automation.PSCredential($User_,$EncryptedPass_)
#$mailcredentials =
$Subject ="'bowkerdownload'"
$To = "XXX"
$From = "XXX"
$body = (get-content -path g:\resultout.txt) -join "`n"
$SMTP = "smtp.office365.com"
#---------File variables here --------------
$month = (Get-Date).AddMonths(-8).ToString('MMM')
$year = (Get-date).addyears(-1).ToString('yyyy')
$filesequential="_*_"
$filesize = "lc"
$filetype = ".txt"
$samlevar=($month + ''+$year + ''+$filesequential + ''+$filesize + ''+$filetype)
$filename = $samlevar.tostring()
#------ The script---------
Set-FTPConnection -Credentials $Credentials -Server $server -Session defaultftpsession -UsePassive
$Session = Get-FTPConnection -Session defaultftpsession
Get-FTPChildItem -Path /Download -filter "$filename" |
Get-FTPItem -session $Session -LocalPath g:\ -Overwrite |
Convertfrom-string -PropertyNames Kode, Status, Action, fil |
Select-Object -Property Status, action, Fil |
Out-file g:\resultout.txt;
Send-MailMessage -To $To -Subject $Subject -Body $Body -SmtpServer $SMTP -From $From -Credential $Mailcredentials -port 587 -UseSsl``
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 = "me#gmail.com"
$EncryptedPW = Get-Content "D:\scripts\gsendcred.txt"
$EncryptedCredential = ConvertTo-SecureString -String $EncryptedCredential -
AsPlainText -Force
$Credential = New-Object Management.Automation.PSCredential ($EmailUsername,
$EncryptedPW)
$EmailFrom = "me#gmail.com"
$EmailTo = "me#gmail.com"
$EmailSubject = "GSEND Test Subject"
$EmailBody = "Test Body"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = 587
$SMTPSsl = $true
I believe your issue is handling credentials. Here is how I handle the smtp credentials:
$smtpPwd = "password"
$smtpCredentialsUsername = "jdonnelly#xxxxx.com"
$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 <recipient#yahoo.com>' -from 'John Donnelly <jdonnelly#xxx.com>'
-cc 'whoever <whoever#xxx.com>' -Subject $subject -Body $body
-BodyAsHtml -smtpserver "smtp.office365.com" -usessl
-Credential (Import-Clixml C:\fso\myemailcreds.xml) -Port 587
You Can use below Powershell script for send mail
Send-MailMessage -To "abc#abc.com" -From "def#abc.com" -Cc "gef#abc.com","hij#abc.com" -Subject Test Mail -BodyAsHtml $htmlbody -SmtpServer "mailhost.abc.com"
where $htmlbody is string variable that contain html.
I want to send a email with powershell. The script works fine if I type my credential in manualy. But I want to give the credential parameters within the script. My script looks like this:
$From = "test#yahoo.de"
$To = "test2#yahoo.de"
$Cc = "test#yahoo.de"
$Attachment = "C:\Users\test\test\test.ini"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.mail.yahoo.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential (
$MyClearTextUsername=’test#yahoo.de’
$MyClearTextPassword=’test123’
$SecurePassword=Convertto-SecureString –String $MyClearTextPassword –AsPlainText –force
$MyCredentials=New-object System.Management.Automation.PSCredential $MyClearTextPassword,$SecurePassword) -Attachments $Attachment
Here's how you can create a credentials object:
$cred = ([pscredential]::new('test#yahoo.de',(ConvertTo-SecureString -String 'test123' -AsPlainText -Force)))
so in your case use:
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $cred -Attachments $Attachment
I see no point in trying to fit that into the Send-MailMessage, just create it before and reference it. easier to read.
If you're using Office365 to send email, you might want to try this:
# Sending an email from PowerShell 5.1 script through outlook.office365.com
#
# 1. Create an encrypted password file
# PS > Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File -FilePath <passwordfile>
# This will prompt you for a password, encrypt and save in <passwordfile>
# 2. Obtain Outlook Office365 SMTP server name.
# Go to your ISP and find the value of the MX record. For example <yourdomain>.mail.protection.outlook.com
# 3. If after running the script you get this error:
# Send-MailMessage : Mailbox unavailable. The server response was: 5.7.606 Access denied, banned sending IP [X.X.X.X].
# You will need to delist your IP by going here: https://sender.office.com/
# Note: Removing you IP from the block list could take up to 30 minutes.
#
$User = "<SMPT loging username>"
$PasswordFile = "<passwordfile>"
$SMTPCredentials=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString)
$EmailTo = "<to email address>"
$EmailFrom = "<from email address>"
$Subject = "<email subject>"
$Body = "<email body>"
$SMTPServer = "<Outlook STMP Server from MX record>"
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port 25 -Credential $SMTPCredentials -UseSsl