Friday, April 27, 2012

Sending Google Docs Document as Email and Viewing in Gmail

Our system uses Google Docs to create and edit documents, which is used as email templates. When we need to send email, we fetch the Google Docs document as HTML (using gdata PHP/Python libraries). And this HTML contents is substituted with data from the database (aka merge fields -- I use smarty to accomplish) and this HTML contents is sent as html email.

All this is fine, but when the mail sent is viewed in Gmail (or probably Hotmail and other web-based email solutions), most HTML decorations are lost and the email is seen in Gmail mostly as text. However, when the same email is viewed using Thunderbird, the email retains all the HTML styles, decorations etc.

After some googling, the following was clear:

  1. Gmail (and others) do not like CSS in the header, but they are somewhat okay with inline styles.
  2. Some of the styles (like font-weight: bold, color within style tags ) etc are stripped out in Gmail loosing the HTML styles for their equivalents. There could be many such styles stripped out, I still don't know the logic of stripping styles like font-weight - but it happens.
  3. Instead of such font-weight styles, they seem to like bold tags (<b>...</b>) etc.
  4. Instead of color styles, they seem to like old font tags (<font color="#xxxxxx">....)
  5. Google Docs sets up styles for a link (anchor) as color:inherit and text-decoration:inherit, which should rather not be there and the default behavior is preferred.
This is the minimum that I needed to get off, there could be various other styles and tags, that need to handled to show in Gmail properly.

The following script in PHP is helpful to move styles inline and then replace some styles with specific tags. 


function move_css_inline($text)
{
    $html = $text;
    if(!preg_match("/\