Search Code Shode

Tuesday, June 1, 2010

Send Email Using Gmail in ASP.NET

using System.Net.Mail;

Now write this code in click event of button

C# Code 

protected void Button1_Click(object sender, EventArgs e)
  MailMessage mail = new MailMessage();
  mail.From = new MailAddress("");
  mail.Subject = "Email using Gmail";

  string Body = "Hi, this mail is to test
          sending mail"+
                "using Gmail in ASP.NET";
  mail.Body = Body;

  mail.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = ""; //Or Your SMTP Server Address
  smtp.Credentials = new System.Net.NetworkCredential
    your Smtp Email ID and Password
  smtp.EnableSsl = true;

VB.NET Code 

Imports System.Net.Mail
Protected  Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
  Dim mail As MailMessage =  New MailMessage() 
  mail.From = New MailAddress("")
  mail.Subject = "Email using Gmail"
  String Body = "Hi, this mail is to test
          sending mail"+ 
                "using Gmail in ASP.NET"
  mail.Body = Body
  mail.IsBodyHtml = True
  Dim smtp As SmtpClient =  New SmtpClient() 
  smtp.Host = "" //Or Your SMTP Server Address
  smtp.Credentials = New System.Net.NetworkCredential
  smtp.EnableSsl = True
End Sub

You also need to enable POP by going to settings > Forwarding and POP in your gmail

Change to your gmail ID and YourGmailPassword to Your password
for Gmail account and test the code.

If your are getting error mentioned below 

"The SMTP server requires a secure connection or the client was not authenticated. The
server response was: 5.5.1 Authentication Required."

then you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your
web.config file.

<proxy proxyaddress="YourProxyIpAddress"/>

If you are still having problems them try changing port number to 587 

smtp.Host = ",587";

If you still having problems then try changing code as mentioned below:

SmtpClient smtp = new SmtpClient();
smtp.Host = "";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
smtp.EnableSsl = true;