Friday, February 25, 2011

Mail in spam? Try (also) this…

Recently some messages from one of my site started being marked as spam by gmail and others.

The particular message is the “confirm registration” one, and it’s easy to understand that it’s imperative that it does not go to the spam folders… if you want regitered users, I mean.

I noticed that in the standard routine that we use to send mail messages there was no setting for the “Message-ID” header. I tried to add it (see below a code sample) and now the “marked as spam” rate is incredibly low!

See here (Wikipedia) a brief explanation of what the particular Message-ID header field is.

Here is the code sample, in bold the three new lines:

private bool PrepareAndSendMail(string emailKey, string senderName, string senderEmail, string destName, string destEmail, StringDictionary args)
{
    try
    {
        MailMessage m = new MailMessage();

        m.From = new MailAddress(senderEmail, senderName);
        m.To.Add(new MailAddress(destEmail, destName));
        m.Subject = MailSettings.Emails[emailKey].Subject;

        // this is to limit the "marked as spam" messages
        Guid messageGuid;
        messageGuid = Guid.NewGuid();
        m.Headers.Add("Message-ID", messageGuid.ToString());

        m.IsBodyHtml = true;
        m.BodyEncoding = Encoding.GetEncoding("iso-8859-1");
        m.Body = ReadTemplateFromFile(Globals.MapPath(MailSettings.Emails[emailKey].Template), args);

        return SendMail(m);
    }
    catch (Exception ex)
    {
        Log.Error("An error occurred sending mail", ex);
        return false;
    }

}

No comments: