How to send mail with multiple attachments in asp.net with C#,Vb.Net

Introduction: In previous articles i explained how to Send email to multiple users based on CheckBox selection inside GridView in asp.net C#,VB.Net and Send emails in asp.net using Gmail | How to set Smtp setting in web.config file to send emails in asp.net using Gmail and Drag & drop to upload multiple files using AjaxFileUpload like Facebook in asp.net and  How to create log file to record errors and exceptions in asp.net.

In this article I am going to explain how to send email with multiple attachments using asp.net in C# and VB.Net. 
send mail with multiple attachment in asp.net

Click on image to enlarge
Description: I have used three FileUpload controls in this example so you can send three attachments with the email. But if you want to send more attachments with email then just add more FileUpload controls as per requirement. There is also option of Cc(Carbon copy) and Bcc( Blank Carbon Copy) option to send mail like Gmail, Yahoo, Rediffmail etc mail servers.

Implementation: Now let’s create the web application to send mail with multiple attachments using SMTP (Simple Mail Transfer Protocol) 

  • In the design page(.aspx) design the form as:

Source Code:

<fieldset style="width:450px;">
        <legend>Send mail with multiple attachments in asp.net</legend>       
        <table>
            <tr>
                <td>From</td>
                <td>
                    <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvFrom" runat="server" ErrorMessage="Email address can't be left blank" ControlToValidate="txtFrom" Display="Dynamic" ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="rgeFrom" runat="server" ErrorMessage="Please enter valid email format" ControlToValidate="txtFrom" ForeColor="#FF3300" SetFocusOnError="True" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic" ></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td>To</td>
                <td>
                    <asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvTo" runat="server" ErrorMessage="Email address can't be left blank" ControlToValidate="txtTo" Display="Dynamic" ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="rgeTo" runat="server" ErrorMessage="Please enter valid email format" ControlToValidate="txtTo" ForeColor="#FF3300" SetFocusOnError="True" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td>Cc</td>
                <td>
                    <asp:TextBox ID="txtCc" runat="server"></asp:TextBox>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtCc" Display="Dynamic" ErrorMessage="Please enter valid email format" ForeColor="#FF3300" SetFocusOnError="True"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td>Bcc</td>
                <td>
                    <asp:TextBox ID="txtBcc" runat="server"></asp:TextBox>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtBcc" Display="Dynamic" ErrorMessage="Please enter valid email format" ForeColor="#FF3300" SetFocusOnError="True"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td>Subject</td>
                <td>
                    <asp:TextBox ID="txtSubject" runat="server" ></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>Attach file</td>
                <td>                   
                    <asp:FileUpload ID="FileUpload1" runat="server" />                   
                </td>
            </tr>
            <tr>
                <td>Attach file</td>
                <td>                    
                    <asp:FileUpload ID="FileUpload2" runat="server" />                   
                </td>
            </tr>
            <tr>
                <td>Attach file</td>
                <td>                   
                    <asp:FileUpload ID="FileUpload3" runat="server" />                   
                </td>
            </tr>
            <tr>
                <td>Body/Message</td>
                <td>
                    <asp:TextBox ID="txtBody" runat="server" Height="89px" TextMode="MultiLine" Width="331px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" OnClick="btnSendMail_Click" />
                    <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
                </td>
            </tr>
        </table>       
    </fieldset>

  • Notice that in this article I have also used the RegularExpression validation control and RequiredFiledvalidator validation control to validate the Email Id’s in the “To”,"Cc","Bcc" and “From” field. To get detailed knowledge on RegularExpression validation control and RequiredFieldValidator validation control read my articles on Validation controls in asp.net.
C#.Net Code to send mail with multiple attachments using asp.net with C# and Vb.Net

Include following namespace:

using System.Net.Mail;

then write the code as:
protected void btnSendMail_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        try
        {          
            mail.To.Add(txtTo.Text.Trim()); // Email address of the recepient 
            mail.CC.Add(txtCc.Text.Trim());// Carbon copy Email address
            mail.Bcc.Add(txtBcc.Text.Trim());// Blank Carbon copy Email address
            mail.From = new MailAddress(txtFrom.Text.Trim(),"Sender Name"); // Email address of the sender and Display name(optional)
            mail.Subject = txtSubject.Text.Trim();  // Email subject
            mail.Body = txtBody.Text.Trim();  //Email body i.e. the content of the email
            mail.IsBodyHtml = true;
            //If the FileUpload Control has file selected. then attaching the  file
            if (FileUpload1.HasFile)
            {
                mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
            }
            if (FileUpload2.HasFile)
            {
                mail.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileUpload2.FileName));
            }
            if (FileUpload3.HasFile)
            {
                mail.Attachments.Add(new Attachment(FileUpload3.PostedFile.InputStream, FileUpload3.FileName));
            }
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com"; //You can also use your SMTP Server Address here
            smtp.Credentials = new System.Net.NetworkCredential("YourGmailId@gmail.com", "YourGmailPassword"); //Or use your Smtp Email ID and Password if Host is not Gmail
            smtp.EnableSsl = true;
            smtp.Send(mail);
            ClearControls();//Clear all controls after sending mail
            lblStatus.Text = "Email sent successfully";
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Email couldn't be sent";
        }      
    }

    protected void ClearControls()
    {
        txtFrom.Text = string.Empty;
        txtTo.Text = string.Empty;
        txtCc.Text = string.Empty;
        txtBcc.Text = string.Empty;
        txtSubject.Text = string.Empty;
        txtBody.Text = string.Empty;  
      }

VB.Net Code to send mail with multiple attachments using asp.net with C# and Vb.Net

Note: Design the form same as C#.Net page(.aspx) above but just change the line <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" OnClick="btnSendMail_Click" /> with  <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" />

Then in code behind file(.aspx.cs) import following namespace:

Imports System.Net.Mail

then write the code as:


Protected Sub btnSendMail_Click(sender As Object, e As EventArgs) Handles btnSendMail.Click
        Dim mail As New MailMessage()
        Try
            mail.[To].Add(txtTo.Text.Trim()) ' Email address of the recepient 
            mail.[CC].Add(txtCc.Text.Trim()) 'Carbon copy Email address
            mail.[Bcc].Add(txtBcc.Text.Trim()) ' Blank Carbon copy Email address       
            mail.From = New MailAddress(txtFrom.Text.Trim(), "Sender Name") ' Email address of the sender and Display name(optional)
            mail.Subject = txtSubject.Text.Trim() ' Email subject
            mail.Body = txtBody.Text.Trim() 'Email body i.e. the content of the email
            mail.IsBodyHtml = True
            'If the FileUpload Control has file selected. then attaching the  file
            If FileUpload1.HasFile Then
                mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))
            End If
            If FileUpload2.HasFile Then
                mail.Attachments.Add(New Attachment(FileUpload2.PostedFile.InputStream, FileUpload2.FileName))
            End If
            If FileUpload3.HasFile Then
                mail.Attachments.Add(New Attachment(FileUpload3.PostedFile.InputStream, FileUpload3.FileName))
            End If
            Dim smtp As New SmtpClient()
            smtp.Host = "smtp.gmail.com" 'You can also use your SMTP Server Address here
            smtp.Credentials = New System.Net.NetworkCredential("YourGmailId@gmail.com", "YourGmailPassword") 'Or use your Smtp Email ID and Password if Host is not Gmail
            smtp.EnableSsl = True
            smtp.Send(mail)
            ClearControls() 'Clear all controls after sending mail
            lblStatus.Text = "Email sent successfully"
        Catch ex As Exception
            lblStatus.Text = "Email couldn't be sent"
        End Try
    End Sub

    Protected Sub ClearControls()
        txtFrom.Text = String.Empty
        txtTo.Text = String.Empty
        txtCc.Text = String.Empty
        txtBcc.Text = String.Empty
        txtSubject.Text = String.Empty
        txtBody.Text = String.Empty
    End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

6 comments

Click here for comments
Unknown
admin
August 26, 2013 ×

hi buddy.. this code attach the file but fail to send that file corresponding mailid

Reply
avatar
August 26, 2013 ×

Hello Dazz Binny..this code is working fine on many sites i developed. Have you passed your gmail credentials i.e. gmail id and password? Please recheck and retry..

Reply
avatar
Varun K.R
admin
September 08, 2013 ×

Its.. working.. Mr. Lalith Thank you very much

Reply
avatar
September 08, 2013 ×

Your welcome Varun K.R..stay connected for more useful updates..

Reply
avatar
Unknown
admin
September 11, 2013 ×

as its working ...but when i add a update panel and update progress under button control, attachment part will not work only this (to,from,cc,bcc,subject and body) part will work.....

So,please reply suitable example

Reply
avatar
September 11, 2013 ×

The FileUpload control doesn’t work for uploading image using Asynchronous postback when placed in the Update Panel since FileUpload control required full postback to get the image.
Read the article to solve this issue:
fileupload control cause problem in update panel
Solution to FileUpload control is not working in UpdatePanel
http://www.webcodeexpert.com/2013/08/fileupload-control-in-update-panel.html

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..