To implement this concept first we need to following reference to our application System.Web.Mail namespace
To add this reference follow below steps.
a) On the Project menu, click Add Reference.
b) On the .NET tab, locate System.Web.dll, and then click Select.
c) Click OK in the Add References.
After that design your aspx page like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Send Mail using asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style=" border:1px solid" align="center">
<tr>
<td colspan="2" align="center">
<b>Send Mail with Attachment using asp.net</b>
</td>
</tr>
<tr>
<td>
From:
</td>
<td>
<asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
To:
</td>
<td>
<asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
<asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Attach a file:
</td>
<td>
<asp:FileUpload ID="fileUpload1" runat="server" />
</td>
</tr>
<tr>
<td valign="top">
Body:
</td>
<td>
<asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Columns="30" Rows="10" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" Text="Send" runat="server" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Now add following namcespace in codebehind
using System.Web.Mail;
After that write the following code in button click
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
MailMessage Msg = new MailMessage();
// Sender e-mail address.
Msg.From = txtFrom.Text;
// Recipient e-mail address.
Msg.To = txtTo.Text;
// Subject of e-mail
Msg.Subject = txtSubject.Text;
if (fileUpload1.HasFile)
{
// File Upload path
String FileName = fileUpload1.PostedFile.FileName;
//Getting Attachment file
MailAttachment mailAttachment = new MailAttachment(FileName, MailEncoding.Base64);
//Attaching uploaded file
Msg.Attachments.Add(mailAttachment);
}
Msg.Body = txtBody.Text;
// your remote SMTP server IP.
SmtpMail.SmtpServer = "10.120.0.21";
SmtpMail.Send(Msg);
Msg = null;
Page.RegisterStartupScript("UserMsg", "<script>alert('Mail sent thank you...');if(alert){ window.location='SendMailWithAttachment.aspx';}</script>");
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
Sakthiae, if this helps please login to Mark As Answer. | Alert Moderator