Wednesday, July 14, 2010

C#.net code to send email using google account

Few days ago I was working on my website. So there I came across the problem of integrating functionality to send email whenever someone fills up the Contact Us form on the website. So while googleing I came across this nice code which can be used to send emails even without worrying about the smtp details of the hosting company. I have implemented this and the code works fine. One just need to copy paste :)


The SendMail function code:

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 call the function :

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

The further details about this code can be found http://1d10tee.blogspot.com/2009/12/code-to-send-email-using-gmail-account.html

Hope this will be helpful