Sending mail from asp.net:
When we are working with mail system we need to have SMTP server, SMTP server will request from web site and will deliver the mail request to other SMTP servers associated with other websites.
Here iis and smtp are servers.when ever any SMTP server will be seen any mail msg then it will send the request of that mail to the web site.
So at the time of sending a mail we need to set our web site as client to the SMTP server prepare a mail msg
and send to smtp server.
To perform this we use three namespaces in asp.net
1)using system.net;
2)using system.net.mail;
3)using system.web.mail;
System.Net:
This namespace contains an important class known as network credentials.
System.Net.Mail:
classes available in the namespaces are
1. Attachment
2.Mail Address.
3.SMTP client
4.SMTP Exception
5.SMTP failed recipient exception
6.SMTP permission
System.Web.Mail:
Classes available in the namespaces are
Mail Attachment
Mail message
SMTP Mail.
By using this we can write a code
Source Code:
<body>
<form id="form1" runat="server">
<div>
<h1 align="center">Sending an Email</h1>
<table align="center">
<tr><td>To:</td><td><asp:TextBox ID="txt1_to" runat="server"></asp:TextBox></td></tr>
<tr><td>subject:</td><td><asp:TextBox ID="txt_sub" runat="server"></asp:TextBox></td></tr>
<tr><td>Body:</td><td><asp:TextBox ID="txt_body" runat="server"></asp:TextBox></td></tr>
<tr><td>Attachment:</td><td><asp:FileUpload ID="fle1" runat="server" /></td></tr>
<tr><td colspan="2" align="center"><asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" /></td></tr>
</table>
</div>
</form>
</body>
</html>
Code Behind:
in an button click event
protected void Button1_Click(object sender, EventArgs e)
{
MailMessage msg = new MailMessage("aswinialuri@gmail.com", txt1_to.Text);
msg.IsBodyHtml = true;
msg.Subject=txt_sub.Text.ToString();
msg.Body=txt_body.Text.ToString();
if(fle1.HasFile)
{
msg.Attachments.Add(new Attachment(fle1.PostedFile.InputStream, fle1.FileName));
}
NetworkCredential nc = new NetworkCredential("aswinialuri@gmail.com", "yourpwd@");
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = nc;
smtp.Send(msg);
}
No comments:
Post a Comment