Friday, October 19, 2012

Send Email from your GMAIL account using ASP.Net and C#

Send Email from your GMAIL account using ASP.Net and C#

Send email using Gmail account

Download Sample

You can use your gmail account to send emails from ASP.Net and C#, using SMTP. You need to set SSL credentials. This is not straight forward like a simple SMTP email. After searching for long hours I was able to find a solution. Use following class to send emails using your GMAIL account.

Please supply your gmail user name and password in following class where needed.

01.using System.Web.Mail;
02.using System;
03.public class MailSender
04.{
05.public static bool SendEmail(
06.string pGmailEmail,
07.string pGmailPassword,
08.string pTo,
09.string pSubject,
10.string pBody,
11.System.Web.Mail.MailFormat pFormat,
12.string pAttachmentPath)
13.{
14.try
15.{
16.System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
17.myMail.Fields.Add
19."smtp.gmail.com");
20.myMail.Fields.Add
22."465");
23.myMail.Fields.Add
25."2");
26.//sendusing: cdoSendUsingPort, value 2, for sending the message using
27.//the network.
28. 
29.//smtpauthenticate: Specifies the mechanism used when authenticating
30.//to an SMTP
31.//service over the network. Possible values are:
32.//- cdoAnonymous, value 0. Do not authenticate.
33.//- cdoBasic, value 1. Use basic clear-text authentication.
34.//When using this option you have to provide the user name and password
35.//through the sendusername and sendpassword fields.
36.//- cdoNTLM, value 2. The current process security context is used to
37.// authenticate with the service.
38.myMail.Fields.Add
40.//Use 0 for anonymous
41.myMail.Fields.Add
43.pGmailEmail);
44.myMail.Fields.Add
46.pGmailPassword);
47.myMail.Fields.Add
49."true");
50.myMail.From = pGmailEmail;
51.myMail.To = pTo;
52.myMail.Subject = pSubject;
53.myMail.BodyFormat = pFormat;
54.myMail.Body = pBody;
55.if (pAttachmentPath.Trim() != "")
56.{
57.MailAttachment MyAttachment =
58.new MailAttachment(pAttachmentPath);
59.myMail.Attachments.Add(MyAttachment);
60.myMail.Priority = System.Web.Mail.MailPriority.High;
61.}
62. 
63.System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
64.System.Web.Mail.SmtpMail.Send(myMail);
65.return true;
66.}
67.catch (Exception ex)
68.{
69.throw;
70.}
71.}
72.}


Example usage of this class,
1.EmailLib.SendEmail.SendEmail("your_gmail_id",
2."your_gmail_password",
3."to_email @ anydomain.com",
4."This is email subject" ,
5."This is email body",
6.Web.Mail.MailFormat.Text,
7."Physical path to your Attachment")

Note: If you do not want to attach a file with email, supply blank string as "".

No comments:

Post a Comment