Introduction:
In this example iam going to explain how to send email in asp.net using Gmail Smtp server.
Description:
To Implement this example First You design your aspx page like this.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sending
Mail using smtp server</title>
</head>
<body>
<form id="form1" runat="server">
<div style="margin-left: 80px; float: inherit;margin-bottom: 25px">
<b>Send Mail
using gmail credentials in asp.net</b>
</div>
<div style="margin-bottom: 5px">
<div style="margin-left: 50px; width: 100px; float: left">
To:
</div>
<div style="margin-left: 50px; float: inherit">
<asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
</div>
</div>
<div style="margin-bottom: 5px">
<div style="margin-left: 50px; width: 100px; float: left">
CC:
</div>
<div style="margin-left: 50px; float: inherit">
<asp:TextBox ID="txtcc" runat="server"></asp:TextBox>
</div>
</div>
<div style="margin-bottom: 5px">
<div style="margin-left: 50px; width: 100px; float: left">
Subject:
</div>
<div style="margin-left: 50px; float: inherit">
<asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
</div>
</div>
<div style="margin-bottom: 5px">
<div style="margin-left: 50px; width: 100px; float: left">
Body:
</div>
<div style="margin-left: 50px; float: inherit">
<asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Columns="30" Rows="10"> </asp:TextBox>
</div>
</div>
<div style="margin-left: 150px">
<asp:Button ID="btnSubmit" Text="Send" runat="server" OnClick="btnSubmit_Click" />
</div>
<asp:Label ID="lblMessage" runat="server" ForeColor="Red" style="margin-left: 250px;"> </asp:Label>
</form>
</body>
</html>
|
In Web.Config add below code after <appSettings/> tag.
<system.net>
<mailSettings>
<smtp from="Your Mail Id">
<network host="smtp.gmail.com" port="587" userName="Your Mail Id" password="YourPassword"/>
</smtp>
</mailSettings>
</system.net>
|
Now you add below namespace in code behind:
using System.Net;
using System.Net.Mail;
Now write the Below code in Code behind.
protected void btnSubmit_Click(object sender, EventArgs e) { try { NetworkCredential NC = new NetworkCredential(); SmtpClient smtp = new SmtpClient(); MailMessage mailmsg = new MailMessage(); mailmsg.Subject = txtSubject.Text; mailmsg.Body = txtBody.Text; mailmsg.To.Add(txtTo.Text); mailmsg.CC.Add(txtcc.Text); mailmsg.IsBodyHtml = true; smtp.EnableSsl = true; NC = (NetworkCredential)smtp.Credentials; smtp.Send(mailmsg); mailmsg = null; lblMessage.Text = "Your email has been sent"; } catch (Exception ex) { lblMessage.Text = ex.ToString(); } } |
If u get any error regarding security remove smtp.EnableSsl = true;
Demo:
|
No comments:
Post a Comment