Sunday, January 13, 2013

Embedding pictures in HTML emails

Following on from my  post from a few days ago about previewing HTML emails, it seems that I prematurely congratulated myself about including pictures in the email. Whilst I could see the pictures in the emails (not only in the preview), other recipients of the emails could not see the pictures.

This was because the pictures were referenced by the "img src" command which assumes that the picture exists on the computer which is reading the HTML code. This works when one is reading an Internet page with a browser, but doesn't work when reading emails - because the picture is not embedded in the email.

In order to find out what command was necessary to do this, I first sent myself an email from Outlook which contained an embedded picture; I soon discovered that the necessary command is still "img src", but instead of accessing/naming a file, it uses a "cid" (content id). But how does one set this value?

There is a very informative page here, but this mainly discusses Indy 10, and I am (of course) using Indy 9. After asking the question on Stack Overflow, along with a bit of to and fro, I saw what I needed to do.

An HTML letter is built of several sections; one of these sections deals with embedded pictures.
if laPicture.text <> '' then
 with TIdAttachment.Create (email.MessageParts, laPicture.text) do
  begin
   ContentDisposition:= 'inline';
   ContentType:= 'image/jpeg';
   DisplayName:= ExtractFileName (laPicture.text);
   filename:= ExtractFileName (laPicture.text);
   ExtraHeaders.Values['Content-ID'] := '<12345>';
 end;

The key line is the one which starts with 'ExtraHeaders' - this assigns a content-ID value to the picture. The text quoted is arbitrary - it could have been the file name or the digit 1; anything will do as long as it is enclosed in angle brackets.

The HTML code for accessing this then becomes
img src="cid:12345"
Several tests confirmed that this was the key to embedding pictures in HTML mails.

The next problem to be overcome is the fact that the subject line of the email sometimes comes out in gibberish. I will address this is a future blog entry.

No comments: