How to Send an E-mail using Gmail in ASP.Net

Vuyiswamb
Posted by in ASP.NET AJAX category on for Beginner level | Views : 16876 red flag
Rating: 5 out of 5  
 3 vote(s)

There are many ways that an application can use to communicate with users. Some users are used to message box popping up and some users are annoyed because this affect the work flow. Some think it’s better to read these messages later. One more thing I saw is that most of the users hate the yellow screen of death. Maybe we need not to show them this message and trap this globally and send this messages t our self.
Introduction

There are many ways that an application can use to communicate with users. Some users are used to message box popping up and some users are annoyed because this affect the work flow. Some think it’s better to read these messages later. One more thing I saw is that most of the users hate the yellow screen of death. Maybe we need not to show them this message and trap this globally and send this messages t our self. One more last scenario is that sometimes users will like to contact you through your website to give you a feedback or complaining about something or send a nice message about how good is your website. All the above scenarios I have mentioned point to e-mail. E-mail is not important only in outlook. But we can use e-mail to make our applications and websites more responsive. We can know what our visitors feel about our work. You can send your send an error received by your client. Before a client report the Problem you might have fixed it. Clients want to hear that you already took care of the problem. Believe I practise what I preach.


Background

In this Article I will show you how to send an e-mail using Gmail smtp. You must have a Gmail Account before you can do this example. Almost all programmers have this account. If you don’t have one you can create it here www.Gmail.com and choose the Signup option.




Using the Code

We are going to user C# as our language.



Start

Open Visual Studio and Create a New Website. Automatically you will have an empty page defined for you like this

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

    </div>

    </form>

</body>

</html>

 

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

        <title>Untitled Page</title>

    </head>

    <body>

        <form id="form1" runat="server">

        <div>

            &nbsp;<br />

            <br />

            <strong>&nbsp;To : </strong>&nbsp; &nbsp; &nbsp;&nbsp; &nbsp;<asp:TextBox ID="txtto"

                runat="server" Width="445px"></asp:TextBox><br />

            &nbsp; &nbsp; &nbsp;&nbsp;

            <br />

            <strong>from: &nbsp;</strong> &nbsp; &nbsp; &nbsp;<asp:TextBox ID="txtfrom" runat="server"

                Width="168px"></asp:TextBox><br />

            <br />

            <strong>Subject:&nbsp;</strong> &nbsp;

            <asp:TextBox ID="txtsubject" runat="server" Width="449px"></asp:TextBox><br />

            <br />

            <strong>Message:&nbsp;</strong><br />

            &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

            <asp:TextBox ID="txtmessage" runat="server" Height="202px" Width="451px"></asp:TextBox>

            &nbsp;<br />

            &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;

            <br />

            &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

            <asp:Button ID="btnSend" runat="server" Text="Send" Width="62px" OnClick="btnSend_Click" />

            <asp:Button ID="btncancel" runat="server" Text="Cancel" /></div>

        </form>

    </body>

    </html>

 

 

The next step is to add a code on our server side. Let us go to our send Button and add the following code

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Net.Mail;

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void btnSend_Click(object sender, EventArgs e)

    {

        MailMessage mm = new MailMessage();

 

        SmtpClient smtp = new SmtpClient();

 

        mm.From = new MailAddress(txtfrom.Text);

 

        mm.To.Add(new MailAddress(txtto.Text));

 

        // mm.To.Add(new MailAddress("moreemail@vuyiswa.co.za"));

 

        mm.Subject = txtsubject.Text;

 

        mm.Body = txtmessage.Text;

 

        mm.IsBodyHtml = true;

 

        smtp.Host = "smtp.gmail.com"; //You can add this in the webconfig

 

        smtp.EnableSsl = true;

 

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

 

        NetworkCred.UserName = "vuyiswamb@gmail.com";

 

        NetworkCred.Password = "wowOops";

        smtp.UseDefaultCredentials = true;

 

        smtp.Credentials = NetworkCred;

 

        smtp.Port = 587; //this is Gmail port for e-mail

 

        smtp.Send(mm);//send an e-mail

    }

}

 

 

When the send button is clicked the e-mail will be send to the receipeint. You can add more e-mail. If the Textbox has e-mails separated by a semicolon then you can split the string and use the semicolon as a delimiter. 



Conclusion

This code can be coded in Exception handling code that is trapped in the global.asa and send an e-mail to yourself than showing the yellow screen of death.

Thank you for visiting DotnetFunda.

Vuyiswa Maseko



Page copy protected against web site content infringement by Copyscape

About the Author

Vuyiswamb
Full Name: Vuyiswa Maseko
Member Level: NotApplicable
Member Status: Member,MVP,Administrator
Member Since: 7/6/2008 11:50:44 PM
Country: South Africa
Thank you for posting at Dotnetfunda [Administrator]
http://www.Dotnetfunda.com
Vuyiswa Junius Maseko is a Founder of Vimalsoft (Pty) Ltd (http://www.vimalsoft.com/) and a forum moderator at www.DotnetFunda. Vuyiswa has been developing for 16 years now. his major strength are C# 1.1,2.0,3.0,3.5,4.0,4.5 and vb.net and sql and his interest were in asp.net, c#, Silverlight,wpf,wcf, wwf and now his interests are in Kinect for Windows,Unity 3D. He has been using .net since the beta version of it. Vuyiswa believes that Kinect and Hololen is the next generation of computing.Thanks to people like Chris Maunder (codeproject), Colin Angus Mackay (codeproject), Dave Kreskowiak (Codeproject), Sheo Narayan (.Netfunda),Rajesh Kumar(Microsoft) They have made vuyiswa what he is today.

Login to vote for this post.

Comments or Responses

Posted by: Chikul on: 12/24/2009
Hi Vuyiswamb,

I tried this one. but its throwing error.
"The remote name could not be resolved: 'smtp.gmail.com' "

Is there any other modifications i need to do .

Even <%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %> also not required i think.

Regards,
Chikul

Posted by: Vuyiswamb on: 2/12/2010
Hi Chikul

You are right that part id not required but its not a trainsmash. i was busy with other things while preparing the article. If you receive this error. It means that your username or Password is not correct. Because the Host and the Port are Correct and they dont change. Try to use your Gmail account. i hope you did not try to use my e-mail and my password because the password is not real.

Thank you for Posting at DotnetFunda

Vuyiswa Maseko

Posted by: Pann on: 7/27/2010
hello
I've got error this message

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.127.109:587

plz reply me how to do this.
Best Regards.
Pann
Posted by: Vuyiswamb on: 7/28/2010
Good Day Pann

Please show me your code and i will what i s wrong for you
Posted by: Rey on: 5/22/2012 | Points: 25
Hi, vuyiswamb I try your code but bind in table
but i got an error
The operation has timed out.
Line 61:
Line 62:
Line 63: smtp.Send(message);
Line 64:
Line 65: }


this is my code

protected void btnMailBlast_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connStr);
con.Open();




SqlCommand cmd_Email = new SqlCommand("SELECT EB_EmailAddress FROM CRM_EmailBlast", con);
SqlDataReader read_Email = cmd_Email.ExecuteReader();

ArrayList emailArray = new ArrayList();

while (read_Email.Read())
{
emailArray.Add(read_Email["EB_EmailAddress"]);
}

foreach (string email in emailArray)
{


SmtpClient smtp = new SmtpClient("smtp.gmail.com");

smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Timeout = 15000;


System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "reyevelarde@gmail.com";
NetworkCred.Password = "revikei";
smtp.UseDefaultCredentials = true;



smtp.Credentials = NetworkCred;
//smtp.Credentials = new System.Net.NetworkCredential("reyevelarde@gmail.com", "revikeivel");

MailMessage message = new MailMessage();
MailAddress toAddress = new MailAddress(email);
message.To.Add(toAddress);
message.Subject = "EMail Blast Testing";
message.From = new MailAddress("reyevelarde@gmail.com");
//message.IsBodyHtml = true;
message.Body = "Test Only";


smtp.Send(message);

}
read_Email.Close();

con.Close();


}

Sorry I'm new in c#.
Posted by: Hemanth.Sutapalli on: 11/7/2012 | Points: 25
hi vuyiswamb,

i tried above code (https://localhost/Default.aspx) i configured this code secure way.. but i got this error...

Server Error in '/' Application.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
Posted by: .Netlearner on: 3/19/2013 | Points: 25
hello, i used your code . No error but i didnt receive mails too.


               MailMessage mm = new MailMessage();


SmtpClient smtp = new SmtpClient();

mm.From = new MailAddress("cartoro2013@gmail.com");

mm.To.Add(new MailAddress(txtemail.text));

// mm.To.Add(new MailAddress("moreemail@vuyiswa.co.za"));

mm.Subject = "Registered Successfully";

mm.Body = "Registered";
System.Net.NetworkCredential credential = new System.Net.NetworkCredential("cartoro2013@gmail.com", "abcd*123");
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = true;
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = true;

smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send("mm");


Please guide me where am going wrong.mail root folder is also empty. and am using iis7

Posted by: Vuyiswamb on: 5/13/2013 | Points: 25
are you sending an email behind a proxy ?

Posted by: Pdoxtader on: 6/21/2013 | Points: 25
Great work! thank you for posting this.

I took the time to convert the c# stuff to vb.net. This is what I did with it - maybe it will help someone out.

Imports System.Data

Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net.Mail

Public Class Emailtester
Inherits System.Web.UI.Page

Public Function SendMail(ByVal fromAddress As String, ByVal toAddress as String,
ByVal subject As String, ByVal body As String, Optional ByRef errMsg As String = "") As Boolean

Dim mm As New MailMessage()
Dim smtp As New SmtpClient()
Dim NetworkCred As New System.Net.NetworkCredential()

Try
NetworkCred.UserName = "YourGmailAccountHere@gmail.com"
NetworkCred.Password = "YourGmailPasswordHere"

With mm
.[To].Add(New MailAddress(toAddress))
.From = New MailAddress(fromAddress)
.Subject = subject
.Body = body
.IsBodyHtml = True
End With

With smtp
.Host = "smtp.gmail.com"
.EnableSsl = True ' You can also add this in the webconfig
.UseDefaultCredentials = True
.Credentials = NetworkCred
.Port = 587
.Send(mm)
End With

Catch ex As Exception
Label1.Text = "There was an error sending your email. The error is: " & ex.Message
errMsg = ex.Message
Return False
End Try

Label1.Text = "Your email has been sent."
Return True

End Function

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SendMail("messages@wherever.com", "targetEmailAddress@wherever.com", "Testing gmail relay using gmail.com", "This email was relayed through gmail.")
End Sub

End Class

Posted by: Vuyiswamb on: 6/21/2013 | Points: 25
if you want to convert code , use this

http://converter.telerik.com/


Login to post response

Comment using Facebook(Author doesn't get notification)