Introduction
In this post I am explain how to Send Email with attachment. In many cases we need to send emails using ASP.NET and also required to send email with attachment. We can send email with attachment with the following steps:
Prerequisite
I used followings:
Steps :
Just follow the steps and get result easily.
Step - 1 : Create New Project
Go to File > New > Project > Select asp.net mvc4 web application > Entry Application Name > Click OK.
Step-2: Add a Web form.
Projects > Add new item > Select Web Form under Web > Enter name > Add.
Write following HTML code to the web form(page) under form tag.
<div>
<table>
<tr>
<td>From : </td>
<td><asp:TextBox ID="txtFrom" runat="server" Width="148px"></asp:TextBox>@gmail.com</td>
</tr>
<tr>
<td>Password : </td>
<td><asp:TextBox ID="txtPassword" runat="server" Width="148px" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td>To : </td>
<td><asp:TextBox ID="txtTo" runat="server" Width="200px"></asp:TextBox></td>
</tr>
<tr>
<td>Subject : </td>
<td><asp:TextBox ID="txtSubject" runat="server" Width="200px"></asp:TextBox></td>
</tr>
<tr>
<td>Message : </td>
<td><asp:TextBox ID="txtMessage" runat="server" Width="200px"></asp:TextBox></td>
</tr>
<tr>
<td>Attachment : </td>
<td><asp:FileUpload ID="FileUpload1" runat="server" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSend" runat="server" Text="Send Mail" OnClick="btnSend_Click" /></td>
</tr>
</table>
</div>
Step-3: Add Folder to Save attached file.
Right Click on ProjectName under Solution Explorer > Add > New Folder > enter folder name.
Here I have added a folder named
EmailAttachment
Step-4: Add Code.
Double click on Send Email button.
Write following code in button click event.
public void Send(string from, string to, string Message, string subject, string host, int port, string password)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(txtFrom.Text.Trim(), password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.To.Add(to);
string fileName = "";
if (FileUpload1.PostedFile != null)
{
HttpPostedFile attchment = FileUpload1.PostedFile;
int FileLength = attchment.ContentLength;
if (FileLength > 0)
{
fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Path.Combine(Server.MapPath("~/EmailAttachment"), fileName));
Attachment attachment = new Attachment(Path.Combine(Server.MapPath("~/EmailAttachment"), fileName));
email.Attachments.Add(attachment);
}
}
smtp.Send(email);
}
Step-5: Run Application.
Enjoy.