do_Ob
do_Ob

Reputation: 719

How to encode the subject of the mail in Powershell?

I am trying to send mail using Powershell with Japanese character on the subject and body of the mail. The mail is successfully sent and the Japanese character in the body is fine. But it is not working in subject. I got =?iso-2022-jp?Q?=1B=24B=25F=259=25H=1B=28B?= instead of テスト.

Can someone help me on this?

code:

$eSubject = "テスト This is subject"
$eBody = "テスト テスト テスト This is body"

$Encode = [Text.Encoding]::GetEncoding("csISO2022JP");
$s64 = [Convert]::ToBase64String($Encode.GetBytes($eSubject), [Base64FormattingOptions]::None)

$Mail = New-Object Net.Mail.MailMessage("[email protected]","[email protected]")
$Mail.Subject = [String]::Format("=?{0}?B?{1}?=", $Encode.HeaderName, $s64)

$View = [Net.Mail.AlternateView]::CreateAlternateViewFromString($eBody, $Encode, [Net.Mime.MediaTypeNames]::Text.Plain)
$View.TransferEncoding = [Net.Mime.TransferEncoding]::SevenBit
$Mail.AlternateViews.Add($View)

$SmtpClient = NEW-OBJECT Net.Mail.SmtpClient("localhost","25")
$SmtpClient.Send($Mail)

Upvotes: 1

Views: 3881

Answers (2)

do_Ob
do_Ob

Reputation: 719

I don't know how. But it is working now, I just remove the encoding for subject.

code:

$eSubject = "テスト This is subject"
$eBody = "テスト テスト テスト This is body"

$Encode = [Text.Encoding]::GetEncoding("csISO2022JP");

$Mail = New-Object Net.Mail.MailMessage("[email protected]","[email protected]")
$Mail.Subject = $eSubject

$View = [Net.Mail.AlternateView]::CreateAlternateViewFromString($eBody, $Encode, [Net.Mime.MediaTypeNames]::Text.Plain)
$View.TransferEncoding = [Net.Mime.TransferEncoding]::SevenBit
$Mail.AlternateViews.Add($View)

$SmtpClient = NEW-OBJECT Net.Mail.SmtpClient("localhost","25")
$SmtpClient.Send($Mail)

Upvotes: 0

DarkLite1
DarkLite1

Reputation: 14745

When using the default CmdLet Send-MailMessage it works fine for me:

$EmailParams = @{
    To          = '[email protected]'
    From        = '[email protected]'
    Subject     = 'テスト This is the subject'
    Body        = 'テスト This is the body'
    SMTPServer  = 'YourSMTPServer'
    Encoding    = 'UTF8'
}
Send-MailMessage @EmailParams

Upvotes: 2

Related Questions