0

I'm using MimeKit to build email body string then pass it to pmta along with list of receivers + placeholders for every receiver, then pmta takes care of merging them. We're missing placeholders in subject when the subject also contains cyrillic characters.

Placeholders are expressed as strings in square brackets, i.e [firstname]

Sample subject with two tokens and few characters in between:

subject = "Message for [firstname] Агф [firstname]";

generates the following string (note the second placeholder, missing because of encoding):

From: ...
Date: ...
Subject: Message for [firstname]
 =?utf-8?b?0JDQs9Cw0YTQvtC90L7QsiDQhtC70LvRjyBbZmlyc3RuYW1lXSDQhtC70LvRjw==?=

This is how I'm building the message:

Encoding useEncoding = Encoding.UTF8;

subject = subject.Replace("\u00A0", " "); // replace nbsp with normal space in case one copied by mistake

var message = new MimeMessage() { Subject = subject };

var bodyText = StripHtmlBody(body);

var textPart = new TextPart(MimeKit.Text.TextFormat.Plain)
{
    ContentTransferEncoding = ContentEncoding.QuotedPrintable
};
textPart.SetText(useEncoding, bodyText);


var htmlPart = new TextPart(MimeKit.Text.TextFormat.Html)
{
    ContentTransferEncoding = ContentEncoding.QuotedPrintable
};
htmlPart.SetText(useEncoding, body);


var multipartAlternative = new MultipartAlternative()
{
    textPart,
    htmlPart
};

message.Body = multipartAlternative;

foreach (var item in headers)
    message.Headers.Add(item.HeaderId, item.HeaderValue);

var tokenMailbox = MailboxAddress.Parse("non-existing-email@domain.com");
message.To.Add(tokenMailbox);
message.Prepare(EncodingConstraint.EightBit, 998);

var messageString = "";
using (var ms = new MemoryStream())
{
    message.WriteTo(ms);
    messageString = useEncoding.GetString(ms.ToArray());
}

messageString = messageString.Replace(tokenMailbox.ToString(), "[ReceiverMailbox]");

// inject in pmta and return...

Message body (text & html) is persisted okay, tokens are there after encryption and everything works as expected, my issue with this is at the subject part.

Is there any advice on how can I overcome this situation where certain tokens/placeholders would be spared by encoding?

Any help is appreciated.

Ermir Beqiraj
  • 867
  • 11
  • 24

1 Answers1

0

You need to decode the subject before doing any string-replacement operations.

jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • I'm probably out of options because the replacement takes place in server, I don't control that. So basically is either compose the message with replacements in client or use unencoded subject, which seems like a bad idea both ways – Ermir Beqiraj Aug 13 '20 at 09:33
  • Surely there are tools you can use on the server to decode the subject. There are MIME parsers written in C, C++, perl, python, ruby, javascript, etc. – jstedfast Aug 13 '20 at 14:19