6.8.09

Send Email Using C# through GMAIL

SEE THIS LINK http://mudassarkhan.wordpress.com/2009/01/09/send-email-using-c/
or

Here I have discussed How to send Emails using C#.

See the function below

public Boolean sendemail(String strTo, string strFrom, string strSubject, string strBody,string strAttachmentPath, bool IsBodyHTML)

{

Array arrToArray;

char[] splitter = { ‘;’ };

arrToArray = strTo.Split(splitter);



MailMessage mm = new MailMessage();





mm.From = new MailAddress(strFrom);

mm.Subject = strSubject;

mm.Body = strBody;

mm.IsBodyHtml = IsBodyHTML;



foreach (string s in arrToArray)

{

mm.To.Add(new MailAddress(s));

}



if (strAttachmentPath != “”)

{

//Add Attachment

Attachment attachFile = new Attachment(strAttachmentPath);

mm.Attachments.Add(attachFile);

}



SmtpClient smtp = new SmtpClient();



try

{



//(4) Send the MailMessage (will use the Web.config settings)

smtp.Host = “YourSmtpServer”;

smtp.EnableSsl = “true/false”; //Depending on server SSL Settings

System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();

NetworkCred.UserName = “Your Email”;

NetworkCred.Password = “Your Password”;

smtp.UseDefaultCredentials = true;

smtp.Credentials = NetworkCred;

smtp.Port = 000;//Specify your port No;



smtp.Send(mm);

mm = null;

smtp = null;

return true;

}

catch (Exception ex)

{

mm = null;

smtp = null;

return false;

}

}





To call this function



protected void Button1_Click(object sender, EventArgs e)

{

//Without Attachment

sendemail(“recepient@abc.com”, “sender@xyz.com”, “Subject”, “Body”, “”, true);



//With Attachment

sendemail(“recepient@abc.com”, “sender@xyz.com”, “Subject”, “Body”, “c:\\mypdf.pdf”, true);}





You can also use threading so that your page does not wait for the email to get send and the users get a quick response and mail is send in background



To do that



protected void Button1_Click(object sender, EventArgs e)

{

System.Threading.Thread threadSendMails;

threadSendMails = new System.Threading.Thread(delegate() { sendemail(“recepient@abc.com”, “sender@xyz.com”, “Subject”, “Body”, “”, true); });

threadSendMails.IsBackground = true;

threadSendMails.Start();



}



Also these are the settings for sending email using Gmail



Host – smtp.gmail.com

SSL – true

PortNo 465 or just comment portNo

UserName – Gmail Email

Password Gmail Password