Welcome to W3Courses
 Like Us on Facebook

Send Email Attachments from a Form using Asp.Net and C#

In order to send email attachements from a form, we first upload the file to a temporary location on the server. We then attach the file to the email message, execute the mail message to sent he email and finally delete the file from the temporary location.

Please follow the following steps to add attchment funtionality to you Asp.Net form using C#.

  1. Add the following code in the beginning of the .aspx file right after the <%@ Page Language="C#" ... tag or in the .aspx.cs file. If placing the code in the.aspx.cs file, please exclude the <script language="c#" runat="server"> and </script> tags.

    <%@ Import Namespace="System.Web.Mail" %>
    <%@ Import Namespace="System.IO" %>

    <script language="c#" runat="server">

    private void btnSend_Click(object sender, System.EventArgs e)
    {
                                              
        MailMessage msg = new MailMessage();
       
        msg.To = "email@yourdomain.com";  /* Replace it with your email */

        if (txtfrom.Text == "")
        {
            msg.From = "Unknown";
        }
        else
        {
            msg.From = txtfrom.Text;
        }
       
        msg.Subject = "Subject of the Email";
        msg.Body = "\n Name: " + txtname.Text + "\n Email: " + txtfrom.Text + "\n Phone: " + txtphone.Text + "\n Message: " + txtcontent.Value;
     
        lblStatus.Text = "Sending..."; 
                                                   
        SmtpMail.SmtpServer = "localhost"; /* Replace localhost with the name of your mail server */
        lblStatus.Text = "Your message has been submitted successfully";

        string strdir = "c:\\attachments\\";  /* Defining the location where the attachment will be stored */
        string strfilename = Path.GetFileName(txtFile.PostedFile.FileName);

        if (txtFile.PostedFile.FileName != "")
        {
            txtFile.PostedFile.SaveAs(strdir + strfilename);
            msg.Attachments.Add(new MailAttachment(strdir + strfilename)); /*Attaching the file to the message */
        }

        try
        {
            SmtpMail.Send(msg);
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Exception Occured: " + ex.ToString();
        }

        if (txtFile.PostedFile.FileName != "")
        {
            File.Delete(strdir + strfilename);  /* Deleting the stored file */
        }
       
        panel1.Visible = false;
        panel2.Visible = true;                                       
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        panel1.Visible = true;
        panel2.Visible = false;
    }
    </script>

  2. Replace email@yourdomain.com with your email address.
  3. Replace Subject of the Email with the subject you want.
  4. Replace localhost with your mail server.
  5. Add the following code to the head section of your web page.

    <script language = "javascript">
    function Tocheck(form) 
    {
        if(MailForm.txtFile.value  == "")
        {
          alert("Please attach a file");
          MailForm.txtFile.focus();
          return false;
        }
        else
          return true;
    }
    </script>

    <style type="text/css">
    .formcolumn1
    {
        text-align: left;
        width: 100px;
    }

    .formtable
    {
        BORDER-RIGHT: 1px solid #000000;
        BORDER-TOP: 1px solid #000000;
        BORDER-LEFT: 1px solid #000000;
        BORDER-BOTTOM: 1px solid #000000;
        font-size: 12px;
        font-family: Arial, Sans-Serif;
        BACKGROUND-COLOR: #efefef;
    }
    </style>

     

  6. Add the following code to the body section of your webpage

    <form id="MailForm" method="post" runat="server" enctype="multipart/form-data" onSubmit="return Tocheck(this)">

    <asp:Panel ID="panel1" Runat="server">
        <table width="550" class="formtable" border="0" align="center">
        <tr>
        <td colspan="2" align="center" style="height: 25px">
            All fields marked with an asterisk (*) are required
        </td>
        </tr>
        <tr>
        <td class="formcolumn1" style="width: 100px">
            Name: *&nbsp;</td>
        <td>
            <asp:TextBox id="txtname" runat="server" Width="300px"></asp:TextBox>
            <asp:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" ErrorMessage="*" 
    ControlToValidate="txtname"></asp:RequiredFieldValidator>
        </td>
        </tr>
       
        <tr>
        <td class="formcolumn1" style="width: 100px">
            E-mail: *&nbsp;</td>
        <td>
            <asp:TextBox id="txtfrom" runat="server" Width="300px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtfrom"
                ErrorMessage="*"></asp:RequiredFieldValidator></td>
        </tr>
       
        <tr>
        <td class="formcolumn1" style="width: 100px">
            Phone:&nbsp;</td>
        <td>
            <asp:TextBox id="txtphone" runat="server" Width="300px"></asp:TextBox>&nbsp;
        </td>
        </tr>
       
        <tr>
        <td class="formcolumn1" valign="top" style="width: 100px">
            Message: *&nbsp;</td>
        <td valign="top">
            <textarea runat="server" id="txtcontent" rows="7" cols="45"></textarea>
            <asp:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ErrorMessage="*" 
    ControlToValidate="txtcontent"></asp:RequiredFieldValidator>
        </td>
        </tr> 
       
        <tr>
        <td class="formcolumn1" valign="top" style="width: 100px">
            Attachment: *&nbsp;</td>
        <td valign="top">
            <input type = "file" id = "txtFile" runat = "server">
        </td>
        </tr> 
        
        <tr>
        <td colspan="2" align="center">
            <asp:Button id="btnSend" runat="server" Text="Submit" onClick="btnSend_Click"></asp:Button>
        </td>
        </tr>
       
        </table>

    <br /><br />

    </asp:Panel>

    <asp:Panel ID="panel2" Runat="server">
    <br /><br />
        <center>
            <h2>
                <asp:Label id="lblStatus" runat="server">
                </asp:Label>
            </h2>
        </center>
    </asp:Panel>

    </form>

Share