Pages

Tuesday, November 6, 2012

An invalid character was found in the mail header

I have faced System.FormatException recently and want to share my solution.
I developed email functionality for multiple projects and never thought I would meet unexpected difficulties at this time. But this exception was waiting for me right at my home PC. I am using Russian Windows 7 64x and this is the root of all evil. Under .Net 2.0 System.Net.Mail somehow cannot create even the simplest mails! Changing to modern .Net is not an option because of system requirements.
So there are only two options left.
First of all I could change system language: Control panel->Regional and Language->Administrative tab->Change system local. It would work, but what about my users? Other option is to remember old deprecated System.Web.Mail.
Here is simplest code snippet:

using net = System.Net.Mail;
using web = System.Web.Mail;
...
static void Main(string[] args)
{
    web.MailMessage mail = new web.MailMessage();
    mail.To = "MAILTO@gmail.com";
    mail.From = "MAILFROM@gmail.com";
    mail.Subject = "this is a test email.";
    mail.Body = "this is my test email body";

    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");

    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "YOURMAIL@gmail.com"); //your username here
    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "PASSWORD"); //your password here
    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 465);
    web.SmtpMail.SmtpServer = "smtp.gmail.com"; //your real server goes here

    web.SmtpMail.Send(mail);
    
    return; //Just as example of previous attempt

    net.SmtpClient smtp = new net.SmtpClient();
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new System.Net.NetworkCredential("YOURMAIL@gmail.com", "PASSWORD");
    smtp.Port = 587;
    smtp.Host = "smtp.gmail.com";
    smtp.EnableSsl = true;

    var mailNet = new net.MailMessage("MAILTO@gmail.com",
                                      "MAILFROM@gmail.com",
                                      "SUBJECT",
                                      "MAIL BODY");

    smtp.Send(mailNet); //Here we got a error... As you see I have not used any non-unicode characters...
}
And there is one more interesting thing. Gmail supports two ports for mails - 465 and 587. For Web.Mail you can use 465 port as Web.Mail using Pop protocol by default and for Net.Mail you can use 587 port as it using IMAP protocol.

No comments:

Post a Comment