John
John

Reputation: 1

How to avoid wrong characters reading UTF-8 emails with Indy 10.6 and Delphi 7

I am reading email with Indy 10.6.1.5187 and Delphi 7.

I have only problems with UTF-8 encoded emails, which translate to wrong characters in the customers computers.

I have read a lot about this problem, but I have not found a solution, except decoding the raw email by myself.

I wonder if there is a way to get correct emails when the sender encodes them in UTF-8.

Thanks.

Upvotes: 0

Views: 1372

Answers (1)

mg30rg
mg30rg

Reputation: 1349

UTF8 string is received like it was an Ansi string. You have to decode it.


You have to receive the message text in an UTF8String (aka. AnsiString aka String in Delphi 7) then convert them from UTF8 to AnsiString or (preferably)WideString. You can use the UFT8Decode() or Utf8ToAnsi() function to decode the email body.

If you use the UFT8Decode() function, you will still need WideString aware controls to display the received message.

If you use the Utf8ToAnsi() function, the result might not contain characters that are not part of the users local codepage.

So you will use something like:

var
  ustrEmailBody: UTF8String;
  wstrDecoded: WideString;
begin
  ... 
  // ustrEmailBody now contains the email body
  wstrDecoded := UTF8Decode(ustrEmailBody);
  SomeUnicodeAwareMemo.Text := wstrDecoded;

or

var
  ustrEmailBody: UTF8String;
  astrDecoded: AnsiString;
begin
  ... 
  // ustrEmailBody now contains the email body
  astrDecoded := Utf8ToAnsi(ustrEmailBody);
  SomeMemo.Text := astrDecoded; // the memo might display '?' in place of unknown characters

For further information see the documentation of the UFT8Decode() or Utf8ToAnsi() functions in the Delphi help.

Upvotes: 2

Related Questions