0

I'm trying to figure out how to best use Powershell to send email. I've been struggling with single quote ' and dashes - turning into question marks ? in the sent email and wondering if someone can help. This is what I have:

    ##############################################################################
    $Letter = Get-Content .\Letter.htm
    $From = "Myaddress@email.com"
    $To = address@email.com
    $Cc = "MyOtherAddress@email.com"
    $Subject = "Subject"
    $Body = @"$Name,

    $Letter
    "@
    $SMTPServer = "smtp.gmail.com"
    $SMTPPort = "587"
    Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
    -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -BodyAsHtml -Credential $Credential

    ##############################################################################

I have also tried:

    $Letter = Get-Content .\Letter.htm -Raw
Christopher Cass
  • 817
  • 4
  • 19
  • 31
  • Does this answer your question? [What is the best way to escape HTML-specific characters in a string (PowerShell)?](https://stackoverflow.com/questions/10082217/what-is-the-best-way-to-escape-html-specific-characters-in-a-string-powershell) – Sage Pourpre Jan 22 '20 at 16:03
  • You need to use : `$body = [System.Web.HttpUtility]::HtmlEncode($body)` – Sage Pourpre Jan 22 '20 at 16:05
  • 1
    The other thing I could conceive is an encoding problem when importing the file, in which case you could try `get-content -Path '.\Letter.html' -Encoding UTF8` but regular dashes should not be a problem so my money is still on HTMLEncode, which will escape html characters that need to be escaped. – Sage Pourpre Jan 22 '20 at 16:14
  • Ugh... I've tried both of these now and still not seeing any difference with the outgoing letter. – Christopher Cass Jan 22 '20 at 17:13
  • 1
    @SagePourpre it was the encoding. I thought I had to add the encoding to the $letter variable, but I needed to add the -Encoding UTF8 parameter to the send-mailmessage. – Christopher Cass Jan 23 '20 at 18:09

1 Answers1

1

Seems to be working for me.

$From = "Myaddress@email.com"
$To = "address@email.com"
$Cc = "MyOtherAddress@email.com"
$Subject = "Subject"
$Body = Get-Content "C:\Users\TestUser\Downloads\StackOverflow.html"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -To $To -Cc $Cc -Subject $Subject -Body "$Body" -BodyAsHtml -Priority High -DeliveryNotificationOption OnFailure -SmtpServer 'smtp.gmail.com' -port $SMTPPort -UseSsl -BodyAsHtml -Credential $Credential
Evan
  • 334
  • 1
  • 6
  • 18