Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email Subject showing Encoding

Tags:

powershell

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?

like image 490
Aman Dhally Avatar asked Jan 26 '26 18:01

Aman Dhally


1 Answers

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 ([email protected]) - I tweaked this from his code at http://powershell.com/cs/media/p/357.aspx)

like image 157
Ben Avatar answered Jan 29 '26 08:01

Ben