3

I am using powershell to send an SMTP mail. The body of the email is from a file. The problem is, when I receive this email, it removes all spaces and linefeeds so it looks ugly.

Outlook client is no removing linebreaks.

My code is as follows:

$smtpserver = "smtpserver"
$from="[email protected]"
$to="[email protected]"
$subject="something"
$body= (Get-Content $OutputFile )
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)

I have even tried to use get-content with -encoding ASCII and couple of others but no help. Can anyone please help?

-

thanks

4 Answers 4

11

Found the answer:

use out-string in when reading the file. i.e.

$body= (Get-Content $OutputFile | out-string )
5

Add HTML line break tag at each end of a line:

$body= (Get-Content $OutputFile) -join '<BR>'
2
  • Hi, This just adds <BR> as simple text at the end of the email.
    – Manjot
    Sep 25, 2011 at 19:29
  • @Manjot, piping to Out-String was my first attemtp that didn't work. I got the body in one line. Your message object is set to IsBodyHTML = $true, so <BR> should render each text in its own line. It worked for me.
    – Shay Levy
    Sep 26, 2011 at 14:55
1

What worked for me was converting the content to HTML as the following:

$html = $result | ConvertTo-Html | Out-String
Send-MailMessage -Credential $mycreds -From "" -To "" -BodyAsHtml $html -Encoding ASCII -Subject "Test" -SmtpServer '' -Port 25
0

If you are using PowerShell v2.0 try Send-MailMessage: http://technet.microsoft.com/en-us/library/dd347693.aspx

The default encoding here will be ASCII. So, to be able to retain the encoding, you may want to try and find the encoding of the file and then set the relevant encoding.

To find encoding of a file, use the script here. http://poshcode.org/2059

Now, combine the above function with Send-MailMessage. For example,

send-mailmessage -from "User01 <[email protected]>" -to "User02 <[email protected]>", "User03 <[email protected]>" -subject "Sending the Attachment" -body (Get-Content C:\somefile.txt) -dno onSuccess, onFailure -smtpServer smtp.fabrikam.com -encoding (Get-FileEncoding C:\somefile.txt)

Remember, Get-FileCoding is not a builtin cmdlet. You need to copy it from the poshcode link.

1
  • Hi, I dont have powershell 2.0. My file's coding is UTF-8 and when I used get-content using -encoding UTF-8, it was no help. I even wrote a new file with ASCII encoding and read it same way but it just doesn't like it. :-(
    – Manjot
    Sep 23, 2011 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.