I'm trying to read the content of a text file into a string variable with powershell in order to use it to send an email (via smtp).
Using Get-Content I have no problem reading the contents of a file into a variable:
$body = Get-Content 'C:\somewhere\some-file.html'
The problem is
Send-MailMessage -To [recipient] -From [sender] -Subject [subject] -Body $body -SmtpServer [ip address]
fails with the message
Cannot convert 'System.Object[]' to 'System.String' required by 'Body' parameter. Specified method not supported.
How can I get the file contents into the variable as a String? I've tried converting the resulting Object[] array to a String by piping the $body variable with Convert-String but with no success.
Edit
To anyone looking for a one-liner, with the help of Mark's answer below here it is:
Send-MailMessage -To recipient#domain.com -From sender#domain.com -Subject "Test" -Body (Get-Content 'C:\somewhere\some-file.html' | Out-String) -SmtpServer 123.456.789.012 -BodyAsHtml
Try:
$body = Get-Content 'C:\somewhere\some-file.html' | Out-String
The problem is probably that Get-Content is creating an array of strings and the -Body parameter is expecting a single string.
The Out-String cmdlet I think would convert it to a single string.
Related
I am trying to send an email message using powershell. That the body of the email will contain the results of the Get-ADuser command I run that is stored in a variable. When I try the code below I get the error "Send-MailMessage : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'. Specified method is not supported."
Is there something wrong with what I am doing here?
$Value = Get-ADUser -Filter * -Properties propery.. | foreach { $_.propery..}
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Value
The -body parameter expects a string to be passed to it. You will need to convert your variable to be type string or manipulate its value to be a string. You can accomplish this in numerous ways.
Send-MailMessage -From $From -To $To -Subject $Subject -Body ($Value | Out-String)
Out-String works here because it takes your object ($Value), which is a single array object containing multiple ADUser objects, and converts it into a single string.
See Out-String for more details.
I have a code in the azure PowerShell workflow runbook. And I have the following code
Send-MailMessage -smtpServer $SMTPServer -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body
the EmailTo is
$EmailTo = "xxx#abc.com;yyy#abc.com"
I get a
Send-MailMessage : An invalid character was found in the mail header: ';'.
At EventStopAlert:5 char:5
error...but if I add just one email, then it works.
So I wanted to know what the email separator is in PowerShell.
I'm not sure if you suggested comma above will work. I have always done this by passing an array of addresses.
$to = #("Address1#company.com","Address2#company.com")
Send-MailMessage -to $to
Please see get-help Send-MailMessage.
Send-MailMessage [-To] <String[]>
It's an array of strings. Take your semi-colon or comma delimited list and split it into an array.
Something like this:
$EmailTo = ($toLine -split ';').Trim()
This would be valid:
$EmailTo = 'xxx#abc.com','yyy#abc.com'
I am having an issue with capturing the results of a variable in acceptable/readable format which are sent through an email.
Following is the script I used,
$body = Search-ADAccount -UsersOnly -AccountExpired -SearchBase 'OU=Test1,OU=TEST,OU=Accounts,DC=home,DC=ac,DC=uk' | select SamAccountName, DistinguishedName, AccountExpirationDate
$emailto = 'test#home.ac.uk'
$emailfrom = 'AD-Accounts#home.ac.uk'
$emailserver = '127.0.0.1'
Send-MailMessage -To $emailto -From $emailfrom -Subject 'Expired Accounts' -Body $body -SmtpServer $emailserver
$body variable output is exactly what I want to see in the email body.
SamAccountName DistinguishedName AccountExpirationDate
-------------- ----------------- ---------------------
jumartin CN=user one,OU=test1,OU=Test,OU=Accounts,DC=home,DC=ac,DC=uk 19/10/2016 00:00:00
ricohvalue CN=user two,OU=test1,OU=TEST,OU=Accounts,DC=home,DC=ac,DC=uk 02/09/2016 00:00:00
However the email comes out blank if there are more than one expired user and if there is one expired user than it comes out in the following format:-
#{SamAccountName=userone; DistinguishedName=CN=user one,OU=test1,OU=test,OU=Accounts,DC=home,DC=ac,DC=uk; AccountExpirationDate=10/19/2016 00:00:00}
All I am looking for is the SamAccountName, DistinguishedName and AccountExpirationDate in a nice line by line format in the body of email.
i dont know how i would capture what i see on the screen within a email. Can someone tell me what am i doing wrong.
Although i don't have Search-ADAccount to test with. Using the similar Get-QADUser from Quest gives me the following error when the CMDlet returns multiple users in an array:
Send-MailMessage : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'.
So best make sure that what you are putting in the body is a string.
Send-MailMessage -To $emailto -From $emailfrom -Subject 'Expired Accounts' -Body ($body | Out-String) -SmtpServer $emailserver
Or convert the table to proper HTML and use the BodyAsHtml parameter.
I'm trying to send emails containing accents via powershell.
If i do the following :
$enc = [System.Text.Encoding]::UTF8
Send-MailMessage -to "Recipient#company.com" -from "Sender#company.com" -subject "test" -body "éèà" -Encoding $enc
It actually works and i get the accents fine in the mail.
BUT, if i do this :
$enc = [System.Text.Encoding]::UTF8
$Body = #"
éèà
"#
Send-MailMessage -to "Recipient#company.com" -from "Sender#company.com" -subject "test" -body $body -Encoding $enc
The email looks like this : éèÃ
I actually need to use the #" "# quotes to send multiple lines mails.
Does anybody have a clue of how i could make this work ?
Thanks for your help !
please try to execute this prior to your script :
$OutputEncoding = [Console]::OutputEncoding
I am using send-mail message to send email to our Support System.
But when it send email it shows the subject line like this screen!
=?us-ascii?Q?R899076:Aman:System Summary ?=
In Subject I am using the variable:
$vUserName = (Get-Item env:\username).Value
$vComputerName = (Get-Item env:\Computername).Value
$subject = "$vComputerName : $vUserName : System Summary"
and then
send-MailMessage -SmtpServer Smtp-local -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority High
But when I recieve this email in Outlook it looks fine any Idea?
Actually this a approx 150 lines script and the body of email and smtp server are already specified in the server.
yes I tried the $subject = "$env:ComputerName : $env:UserName : System Summary" variable and the result is same.
yes I have tried the - encoding option and it gives an error
Send-MailMessage : Cannot bind parameter 'Encoding'. Cannot convert the "utf8" value of type "Syste
m.String" to type "System.Text.Encoding".
At D:\PowerShell\MyScripts\SystemInfo\SysInfo-V6-test[notfinal].ps1:151 char:84
+ send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Encoding <<<< utf8 -B
ody $body -Attachments "$filepath\$name.html" -BodyAsHtml -Priority High
+ CategoryInfo : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.SendMai
lMessage
Any clue?
You could write a custom function to send using .net instead of using the Send-MailMessage cmdlet. It's a lot clunkier, but gets round the problem.
Something like this:
Function SendEmail ($emailFrom, $emailTo, $subject, $body, $attachment) {
# Create from/to addresses
$from = New-Object System.Net.Mail.MailAddress $emailFrom
$to = New-Object System.Net.Mail.MailAddress $emailTo
# Create Message
$message = new-object System.Net.Mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = $body
$attachment = new-object System.Net.Mail.Attachment($attachment)
$message.Attachments.Add($attachment)
# Set SMTP Server and create SMTP Client
$server = <your server>
$client = new-object system.net.mail.smtpclient $server
# Send the message
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
"Message to: {1}, from: {0} has beens successfully sent" -f $from, $to
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}
}
(Thanks to Thomas Lee (tfl#psp.co.uk) - I tweaked this from his code at http://powershell.com/cs/media/p/357.aspx)
The Send-MailMessage cmdlet doesn't have any output after you send emails, I wonder where the output comes from? Can you include the command you use and the output?
As to your subject line, you can reduce it to one line only:
$subject = "$env:ComputerName : $env:UserName : System Summary"
The Send-MailMessage has an Encoding parameter, have you tried it?
This happened to me when I used Send-MailMessage with the default encoding (ASCII) when there were spaces in the subject.
First, to answer the question about the Encoding parameter: You are trying to pass it as a string (ie "-Encoding ASCII"), when you should be using this type of syntax instead: "-Encoding ([System.Text.Encoding]::ASCII)".
This "encoding in the subject" issue happened to me, and I narrowed it down to spaces in the subject. To demonstrate:
This will not contain encoding in the subject:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::ASCII)
But this will:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one two" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::ASCII)
Note that the only material difference is the space in the subject.
If I specify UTF8 as the encoding, there is no encoding in the subject:
Send-MailMessage -To "alice#example.com" -From "bob#example.com" -Smtp "localhost" -Subject "one" -BodyAsHtml "body1" -Encoding ([System.Text.Encoding]::UTF8)
But as you say, it looks fine in Outlook, so I presume that the subject is correct. I'm not an expert on email formats or text-encoding, so I won't speculate as to why.