Friday, January 6

Sending email with attachment in ASP.NET


In this article, I am going to describe how to send email with attachment in ASP.NET. I am going to use System.IO, System.Net and System.Net.Mail namespaces in this article.

Download


 Download source code for Sending email with attachment in ASP.NET
 To show the solution, I have prepared a sample asp.net form that looks like below.

Create a Send Email with Attachment form

Copy-paste below code in your .aspx page.
<table>
<tr><td colspan="2"><h3>Send Email with Attachment in ASP.NET</h3></td></tr> <tr><td>To</td><td><asp:TextBox ID="txtTo" runat="server" /></td></tr> <tr><td>Subject</td><td><asp:TextBox ID="txtSubject" runat="server" Columns="30" /></td></tr> <tr><td>Body</td><td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Rows="10" Columns="50" /></td></tr> <tr style="font-weight:bold;"><td>Attachment</td><td><asp:FileUpload ID="FileUpload1" runat="server" /></td></tr> <tr><td>&nbsp;</td><td><asp:Button ID="btnSubmit" runat="server" Text="Send Email" OnClick="SendEmailWithAttachment" /></td></tr>
</table> <asp:Label ID="lblMessage" runat="server" EnableViewState="false" />
This code snippet shall create a Send Email form that looks like above picture. Notice that on click on the button I have attached a server side click event that will fire SendEmailWithAttachment method, so let's write code for that.
protected void SendEmailWithAttachment(object sender, EventArgs e)
{
SendEmail(txtTo.Text.Trim(), "", "", txtSubject.Text.Trim(), txtBody.Text.Trim(), MailPriority.High, false);
}
In the above code, I have fired a SendEmail private method that will actually do the work of sending email. Below is the code for the SendEmail method.
Namespace to use
To work with SendEmail method code, you need to use following namespaces and codes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Net;
using System.Net.Mail;


public partial class SendEmailWithAttachment_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void SendEmailWithAttachment(object sender, EventArgs e)
    {
        SendEmail(txtTo.Text.Trim(), "", "", txtSubject.Text.Trim(), txtBody.Text.Trim(), MailPriority.High, false);
    }

    private void SendEmail(string toAddress, string ccAddress, string bccAddress, string subject, string body, MailPriority priority, bool isHtml)
    {
      
        try
        {
            using (SmtpClient smtpClient = new SmtpClient())
            {
                using (MailMessage message = new MailMessage())
                {

                   // MailAddress fromAddress = new MailAddress("fromEmail@MyDomain.com", "FromEmail, myDomain.Com");
                    MailAddress fromAddress = new MailAddress("dotnetshibashish@gmail.com", "dotnetshibashish, gmail.Com");
                    // You can specify the host name or ipaddress of your server
                    //smtpClient.Host = "smtp.mydomain.com"; //you can also specify mail server IP address here
                    smtpClient.Host = "smtp.gmail.com";
                    //Default port will be 25
                   // smtpClient.Port = 25;
                    smtpClient.Port =587;
                    //

                    smtpClient.EnableSsl = true;
                    System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                    NetworkCred.UserName = "dotnetshibashish@gmail.com";
                    NetworkCred.Password = "password123!";
                    //NetworkCred.UserName = "xyz@shibashish.com";
                    // NetworkCred.Password = "Password123!";
                    smtpClient.UseDefaultCredentials = true;
                    //smtp.Credentials = NetworkCred;
                    smtpClient.Credentials = new System.Net.NetworkCredential("dotnetshibashish@gmail.com", "password123!");

                    //i have added this again for secure network credential
                    NetworkCredential info = new NetworkCredential("dotnetshibashish@gmail.com", "password123!");
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = info;

                    //From address will be given as a MailAddress Object
                    message.From = fromAddress;
                    message.Priority = priority;
                    // To address collection of MailAddress
                    message.To.Add(toAddress);
                    message.Subject = subject;

                    if (ccAddress.Length > 0)
                    {
                        message.CC.Add(ccAddress);
                    }

                    if (bccAddress.Length > 0)
                    {
                        message.Bcc.Add(bccAddress);
                    }

                    //Body can be Html or text format
                    //Specify true if it is html message
                    message.IsBodyHtml = isHtml;

                    // Message body content
                    message.Body = body;
                  
                    // Add the attachment, if any
                    if (FileUpload1.PostedFile.ContentLength > 0)
                    {
                        string path = FileUpload1.PostedFile.FileName;
                       // Attachment attachment = new Attachment(Path.GetFullPath(path));
                        Attachment attachment = new Attachment(Server.MapPath(path));
                        message.Attachments.Add(attachment);
                     
                    
                    }
                  
                    // Send SMTP mail
                    smtpClient.Send(message);
                    lblMessage.Text = "Email sent to " + toAddress + " successfully !";
                }
            }

        }
        catch (Exception ee)
        {
            lblMessage.Text = ee.ToString();
        }
    }
  
}



The above attachment file give error as secure network credential for that you just copy above code behind and paste in your project.



Thanks 
Shibashish mohanty

3 comments:

  1. Compilation Error
    Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

    Compiler Error Message: CS1674: 'System.Net.Mail.SmtpClient': type used in a using statement must be implicitly convertible to 'System.IDisposable'

    Source Error:


    Line 92: try
    Line 93: {
    Line 94: using (SmtpClient smtpClient = new SmtpClient())
    Line 95: {
    Line 96: using (MailMessage message = new MailMessage())


    Source File: d:\practice\webattachmentmail\attachment.aspx.cs Line: 94

    ReplyDelete
  2. plz solve this problem as soon as possible..

    ReplyDelete
  3. error in

    using (SmtpClient smtpClient = new SmtpClient())


    this line

    ReplyDelete

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty