How to fix encoding with send-MailMessage in powerShell? - powershell

I'm trying to send email message from a powershell script but in the email all accented characters (ó, é etc) get scrambled.
What I'm doing is the following:
I use Import-CSV to import an ANSI encoded file.
foreach($item in $inputfile) send-MailMessage -Body $item.body -bodyAsHTML
I'm not a PC-user and the whole encoding thingy gives me headache.
I tried all the different encoding options of send-MailMessage without getting the expected result.

Related

Send emails with Powershell mailto with formated text

My current script creates (after an account modification) a .ps1 file that is send to another computer and there it is executed opening a new Gmail tab with some information hosted in several variables. I need this email to have format like bold, hyper-link, etc.
Im using the start-process 'mailto' for this but i can not find the way to give this email a format (believe me, i have tried), is this even possible?
I appreciate any insights on this.
My current script creates (after an account modification) a .ps1 file that is send to another computer and there it is executed opening a new Gmail tab with some information hosted in several variables. I need this email to have format like bold, hyper-link, etc.
Im using the start-process 'mailto' for this but i can not find the way to give this email a format (believe me, i have tried), is this even possible?
Additional information:
Code:
$outPut = 'Start-Process'
$outPut+= '"mailto:'+$userMail+"?Subject=Password Reset"+"&Body=Hi, your password is $Password"
$outPut+= '";'
$mailFile = "Path" + $user.SAM + ".ps1"
$outPut | Out-File $mailFile
So, this takes the information this way and stored it in a ps1 file, then executed, opening a new Gmail tab with proper data.
I need that some words has format, bold for the password or hyper-link for guideness link...
Regards!
You haven't provided any indication of what you are doing. But the way to send emails via PowerShell is with the Send-MailMessage cmdlet. If you are using Send-MailMessage and formatting the body of the message with HTML, you just need to make sure you are using the -BodyAsHtml argument.
Here's an example:
$html = "<body><h1>Heading</h1><p>paragraph.</p></body>"
Send-MailMessage -To "bob#fake.com" -From "me#fake.com" -Subject "Test" -Body $html -BodyAsHtml

Sent email converts unicode characters into mojibake

I have a mail script sending automated messages to agents about tickets, but Swedish extended characters are being garbled in the script. The text is garbled even when I send it to console instead of emailing.
My research indicates that strings in PowerShell are in UTF16, so I expected things to be preserved... alas, mojibake.
I started with Net.Mail.SmtpClient and that didn't work. I switched to Send-MailMessage because of the -Encoding parameter, but that doesn't change anything for me. I've messed around with the $OutputEncoding variable in case that had something to do with something, but no luck.
So, for example (assuming this doesn't get mangled here either):
The extended characters from the Sweedish alphabet are ÅÄÖåäö
And they get rendered as ÅÄÖåäö
#$encod = ([System.Text.Encoding]::UTF8);
$encod = ([System.Text.Encoding]::Unicode);
$OutputEncoding = $encod;
[string]$message = 'ÅÄÖåäö';
$emailFrom = "Example <EXAMPLE#SAMPLE.COM>";
$emailTo = "Test <TEST#SAMPLE.COM)";
$subject="Långtidsspara";
$smtpserver="smtp.SAMPLE.COM";
#$smtp=New-Object Net.Mail.SmtpClient($smtpServer);
#$smtp.Send($emailFrom, $emailTo, $subject, $message) ;
Send-MailMessage -Body $message -Encoding $encod -From $emailFrom -SmtpServer $smtpserver -Subject $subject -To $emailTo
Edited to add: Previously when I was trying the Net.Mail.SmtpClient() I was doing the following:
$smtp=New-Object Net.Mail.SmtpClient($smtpServer);
$smtp.Send($emailFrom, $emailTo, $subject, $message);
but I couldn't find a way to adjust the encoding.
EDIT 2: thanks to #RemyLebeau I have tried setting the message up as a MailMessage object and using SmtpClient to send that, but no change in behavior.
$smtp=New-Object Net.Mail.SmtpClient($smtpServer);
$mail=New-Object Net.Mail.MailMessage($emailFrom, $emailTo, $subject, $message);
$mail.BodyEncoding = $encod;
$mail.HeadersEncoding = $encod;
$mail.SubjectEncoding = $encod;
$mail.BodyTransferEncoding = [System.Net.Mime.TransferEncoding]::EightBit;
$smtp.SendMailAsync($mail);
EDIT 3: After correcting from UTF16 to UTF8, my email headers say the following
Subject: =?utf-8?B?SW5zcGVsbmluZ3NkYXRhIChMw4PCpW5ndGlkc3NwYXJhKQ==?=
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
But it's all still garbled. I've got Outlook 365 here, but I get emails from Europe all the time, including previous emails from a customer with Å in their name, and Outlook seems to cope?

Powershell using string and file content in email message body without breaking formatting

I have a Powershell script that has a part which needs to email some information. I have a requirement to include 2 pieces of information inside the message body, but I am having issues with formatting. The first part will be a line of text which I would like to simply store inside the powershell script as a variable, and the second part will be information from a text file. Below is a simplified version of what I want to do:
$INFO1="The following fruits are ready to eat:
"
$INFO2=get-content "info2.txt"
$BODY=$INFO1 + $INFO2
$BODY=$BODY | out-string
send-mailmessage -To myname#mydomain.com -Subject "Fruit Status" -From
fruit#mydomain.com -Body $BODY -Smtpserver smtp.mydomain.org -UseSsl
The file info2.txt contains the following info. 3 columns with a list of fruits with tab separators:
Col1 Col2 Col3
Apple Orange Pear
Banana Grape Strawbery
Kiwi Peach Apricot
The above code works but I get an email which looks like this:
The following fruits are ready to eat:
Col1 Col2 Col3 Apple Orange Pear Banana Grape
Strawbery Kiwi Peach Apricot
It keeps the line spaces in the $INFO1 stored variable string, but then places the content of the info2.txt file all in one continuous line, with no line breaks or tabbed formatting.
I tested this with the below changes whereby the line of text from the $INFO1 variable, is instead obtained by doing a get-content on the same piece of text from inside a file named "info1.txt". When I then append both pieces of information into the message body, the formatting is maintained and the email looks ok.
$INFO1=get-content "info1.txt"
$INFO2=get-content "info2.txt"
$BODY=$INFO1 + $INFO2
$BODY=$BODY | out-string
send-mailmessage -To myname#mydomain.com -Subject "Fruit Status" -From
fruit#mydomain.com -Body $BODY -Smtpserver smtp.mydomain.org -UseSsl
The following fruits are ready to eat:
Col1 Col2 Col3
Apple Orange Pear
Banana Grape Strawbery
Kiwi Peach Apricot*
I also notice that if I do the below using the first method, grabbing the file content first and THEN the string from variable, the formatting is also kept fine:
$BODY=$INFO2 + $INFO1
It is only when I start with the string from variable first, that it mucks up the formatting in the email for the file content part.
I would prefer to keep the script more compact and minimize writing out to files on disk and used stored variables. Is there a way I can use method 1 appending a string or multiple strings, followed by file content where formatting is kept? I do not wish to use HTML for this as it will overly complicate matters with the text file content I am working with so the body is just -body rather than -bodyashtml unless this is the only way to sort this.
I believe I have found the answer. I played with the get-content -RAW argument before but I think I was having trouble using it to get content stored in the pipeline. When I use it as below directly on a file with no other where clauses, it fixes the issue:
$INFO1="The following fruits are ready to eat:
"
$INFO2=get-content "info2.txt" -raw
$BODY=$INFO1 + $INFO2
$BODY=$BODY | out-string
send-mailmessage -To myname#mydomain.com -Subject "Fruit Status" -From
fruit#mydomain.com -Body $BODY -Smtpserver smtp.mydomain.org -UseSsl
Get-Content gets the content of the item at the location specified,
such as the text in a file. By default PowerShell will read the
content one line at a time and return a collection of System.String
objects. Carriage returns (CR/LF) are stripped from the original file
but when PowerShell displays a collection of strings, it will
re-insert carriage returns so that the display will look just like the
original file.
If you specify -raw, this behaviour is reversed and the entire file
will be read at once.

Outputting CSV to String/Table

I have a CSV with data that is to be emailed to me at the end of a powershell script. I know that I can attach the CSV file to the email itself, but I'd like to know how to output the data from the CSV straight into the body, formatted properly. I assume that this would involve converting the CSV to a String or something.
I've tried things like ConvertTo-Csv along with Format-Table, but this comes up without formatting. I've thought of looping through the csv line-by-line but I'm not sure where to go from there.
You need to use ConvertTo-Html
$body = $YOUR_CSV_DATA | ConvertTo-Html -Fragment
Send-MailMessage -To 'abc#example.com' -From 'admin#example.com' -Subject 'Your report' -BodyAsHtml -Body $body -SmtpServer 'smtp.example.com'

Powershell: Convert email string to valid format for Send-MailMessage cmdlet

So I'm trying to read in a field in a CSV file that contains multiple email addresses, and then use the Send-MailMessage cmdlet to send to those addresses. The string of addresses looks like this in the CSV file.
john.doe#domain.com;jane.doe#domain.com
The valid format to send is:
("john.doe#domain.com", "jane.doe#domain.com")
Does anyone have a good way of transforming the original string to a valid format?
Thanks again everybody!
You can use the PowerShell -Split operator like such:
$emailstring = 'john.doe#domain.com;jane.doe#domain.com';
$emailarray = $emailstring -split ';';
Send-MailMessage -To $emailarray ... ...;