First you need to add the reference to the system.net. After adding the reference, add the following source code in the default.aspx shown as follows:
<table>
<tr>
<td colspan="2" align="center">Sending mail using asp.net</td>
</tr>
<tr><td>From:</td>
<td><asp:textbox id="FromTextBox" runat="server"></asp:textbox></td>
</tr>
<tr>
<td>To:</td>
<td><asp:textbox id="ToTextBox" runat="server"></asp:textbox></td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:textbox id="SubTextBox" runat="server"></asp:textbox></td>
</tr>
<tr>
<td>Body:</td>
<td><asp:textbox id="BodyTextBox" textmode="MultiLine" runat="server" rows="10" columns="20"></asp:textbox></td>
</tr>
<tr>
<td>File Attachment:</td>
<td><asp:fileupload id="fuAttachment" runat="server" /></td>
</tr>
<tr>
<td colspan="2"><asp:button id="SubmitButton" runat="server" text="Submit" onclick="SubmitButton_Click" /> <asp:label id="ResultLabel" runat="server"></asp:label></td>
</tr>
</table>
And add the code behind as follows, in the default.aspx.cs
protected void SubmitButton_Click(object sender, EventArgs e)
{
try
{
using (MailMessage mm = new MailMessage(FromTextBox.Text, ToTextBox.Text, SubTextBox.Text, BodyTextBox.Text))
{
if (fuAttachment.HasFile)
{
string filename = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, filename));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential netcred = new NetworkCredential("honey.chawla21", "@postpade@");
smtp.UseDefaultCredentials = true;
smtp.Credentials = netcred;
smtp.Port = 587;
smtp.Send(mm);
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email Sent');", true);
}
}
catch (Exception ex)
{
ResultLabel.Text = ex.Message.ToString();
}
}
After adding all these codes, just run this code by pressing F5 and see the result.