How to send email using gmail SMTP Server in Asp.Net?

In this article we will learn how to send email using gmail SMTP Server in ASP.Net.We will use Gmail service to send mail.
Send email in asp.net
In order to send emails with Gmail SMTP Server,what you will need is to have a valid Gmail account and along with that you will need the Gmail SMTP Mail Server settings.
First we will create a public method to send email and use this method in our C# code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
protected string SendEmailMessage(string toAddress, string MessageSubject, string MessageBody)
   {
     string result = "Message Sent Successfully..!!"";
     string senderEmailID = "Enter sender's email id here";
     const string senderPassword = "Enter Sender's Password here";
     try
     {
       SmtpClient smtp = new SmtpClient
       {
         Host = "smtp.gmail.com", // smtp server address here…
         Port = 587,  // this is port number of gmail SMTP server
         EnableSsl = true,
         DeliveryMethod = SmtpDeliveryMethod.Network,
         Credentials = new System.Net.NetworkCredential(senderEmailID, senderPassword),
         Timeout = 20000,
       };
       MailMessage message = new MailMessage(senderEmailID, toAddress, MessageSubject, MessageBody);
       smtp.Send(message);
     }
     catch (Exception ex)
     {
       result = "Error had occured while sending email.!!!"";
     }
     return result;
   }
]]

For learning purpose i have used email credentials in method itself.You can also set all settings in web.config file.
1
2
3
4
5
<appsettings>
 <add key="senderEmailID" value="senderz3@gmail.com"/>
 <add key="Password" value="33423523520"/>
 <add key="Host" value="smtp.gmail.com"/>
</appSettings>
To use these Appsettings use below code in your C# code.
1
2
3
4
ConfigurationManager.AppSettings["senderEmailID"].ToString();
 ConfigurationManager.AppSettings["Password"].ToString();
 ConfigurationManager.AppSettings["Host"].ToString();
]] >

What you need is to use below two settings.Gmail always uses SSL/TLS authentication,hence you need to enable the SSL property on port 587 or 465 to send email in Asp.net using C# or VB.
Port – 587 or 465
EnableSsl – true


Hope you have liked this topic.


Thanks.

How to send email using gmail SMTP Server in Asp.Net? How to send email using gmail SMTP Server in Asp.Net? Reviewed by CodiBucket on 04:48 Rating: 5

No comments:

Powered by Blogger.