Recommended hosting
Sep 30 2006

Send mail from ASP.NET using your gmail account

Posted by admin under ASP.NET articles

In this article we created a generic ASP.NET SendMail function - which I thought should fit most scenarios. I.e authentication/no authentication, localhost/remote host etc.

However, one thing the function can't do is SSL authentication. Lets add that:



public static void SendMail(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sHeader, string sMessage, bool fSSL)
{
    if (sToName.Length == 0)
        sToName = sToEmail;
    if (sFromName.Length == 0)
        sFromName = sFromEmail;

    System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();
    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
    if ( fSSL )
        Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";    

    if (sUserName.Length == 0)
    {
        //Ingen auth
    }
    else
    {
        Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
        Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
        Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
    }

    Mail.To = sToEmail;
    Mail.From = sFromEmail;
    Mail.Subject = sHeader;
    Mail.Body = sMessage;
    Mail.BodyFormat = System.Web.Mail.MailFormat.Html;

    System.Web.Mail.SmtpMail.SmtpServer = sHost;
    System.Web.Mail.SmtpMail.Send(Mail);
}



Now, the secret is the last parameter, bool fSSL. If true then we set the magic CDO field cdo/configuration/smtpusessl  to true:



    if ( fSSL )
        Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";    


And that my folks is all we need. Specify true as last parameter and you will have SSL authentication. Which gmail for example uses so look at this example:



            SendMail("smtp.gmail.com",
                465,
                "account@gmail.com",
                "<accountpassword>",
                "Your name",
                "account@gmail.com",
                "Stefan Receiver",
                "receive@whatever.com",
                "Test",
                "Hello there Steff!",
                true);



So secret to get mail working against gmail is: port 465 - server smtp.gmail.com and ssl = true.