Header Ads

Send email with multiple attachments using Multiple FileUpload control in ASP.Net 4.5

The multiple files to be send as attachments along with mail will be uploaded using ASP.Net 4.5 Multiple FileUpload control and will be dynamically added as attachment in the MailMessage class object without saving in any folder on disk.



This article will make use of Gmail SMTP Mail Server for sending emails, to send email with Gmail SMTP Server, you will need to use an email address and password of a valid Gmail account and along with that you will need the Gmail SMTP Mail Server settings.


In this article I will explain with an example, how to send email with multiple attachments using Multiple FileUpload control in ASP.Net 4.5 using C# and VB.Net.
The multiple files to be send as attachments along with mail will be uploaded using ASP.Net 4.5 Multiple FileUpload control and will be dynamically added as attachment in the MailMessage class object without saving in any folder on disk.
This article will make use of Gmail SMTP Mail Server for sending emails, to send email with Gmail SMTP Server, you will need to use an email address and password of a valid Gmail account and along with that you will need the Gmail SMTP Mail Server settings.
HTML Markup
The following HTML Markup consists of ASP.Net TextBoxes, Multiline TextBox, Password TextBox and Multiple FileUpload control which are used to capture the details of the email to be sent.
There’s also a Send Button which when clicked, the email is sent.
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td style="width: 80px">To:</td>
        <td><asp:TextBox ID="txtTo" runat="server"></asp:TextBox></td>
    </tr>
    <tr><td>&nbsp;</td></tr>
    <tr>
        <td>Subject:</td>
        <td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td>
    </tr>
    <tr><td>&nbsp;</td></tr>
    <tr>
        <td valign="top">Body:</td>
        <td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Height="150" Width="200"></asp:TextBox></td>
    </tr>
    <tr><td>&nbsp;</td></tr>
    <tr>
        <td>File Attachments:</td>
        <td><asp:FileUpload ID="fuAttachment" runat="server" AllowMultiple="true"/></td>
    </tr>
    <tr><td>&nbsp;</td></tr>
    <tr>
        <td>Gmail Email:</td>
        <td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
    </tr>
    <tr><td>&nbsp;</td></tr>
    <tr>
        <td>Gmail Password:</td>
        <td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox></td>
    </tr>
    <tr><td>&nbsp;</td></tr>
    <tr>
        <td></td>
        <td><asp:Button ID="btnSend" Text="Send" OnClick="SendEmail" runat="server"/></td>
    </tr>
</table>
MailMessage Class Properties
Following are the required properties of the MailMessage class.
From – Sender’s email address.
To – Recipient(s) email address.
CC – Carbon Copies (if any).
BCC – Blind Carbon Copies (if any).
Subject – Subject of the email. 
Body – Body of the email.
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments (if any).
ReplyTo – ReplyTo email address.
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL (Gmail: smtp.gmail.com).
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True).
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password).
Port – Port Number of the SMTP server (Gmail: 587).


Namespaces

You will need to import the following namespaces.
C#
using System.IO;
using System.Net;
using System.Net.Mail;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Sending email with attachment using Gmail SMTP Account
Below is the code to send email using Gmail account and Gmail SMTP Server in ASP.Net, the Recipient email address (to), the Sender email address (from), Subject and Body is fetched from their respective fields.
Then all these values are set into an object of the MailMessage class.
For attaching multiple File as attachment to the email, one has to select the Files to be send as attachment using ASP.Net Multiple FileUpload control.
If the ASP.Net Multiple FileUpload control has attachment then the attachment is added to the Attachments List of the MailMessage Object.
You will notice that the File is directly added as attachment without saving it on disk, this is possible since the file data is extracted from the FileUpload PostedFile InputStream property which belongs to the type System.IO.Stream. The second parameter supplied is the name of the File that has to be send as attachment which is extracted from the FileUpload control PostedFile FileName property.
After that an object of the SmtpClient class is created, where we need to set the settings of the Mail Server here Gmail is the Mail Server so we will set the Mail Settings of the Gmail SMTP Server.
NoteIt is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be equal to Gmail Username specified in credentials.
C#
protected void SendEmail(object sender, EventArgs e)
{
    string to = txtTo.Text;
    string from = txtEmail.Text;
    string subject = txtSubject.Text;
    string body = txtBody.Text;
    using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
    {
        mm.Subject = txtSubject.Text;
        mm.Body = txtBody.Text;
        if (fuAttachment.HasFile)
        {
            foreach (HttpPostedFile file in fuAttachment.PostedFiles)
            {
                string fileName = Path.GetFileName(file.FileName);
                file.SaveAs(Server.MapPath("~/Uploads/") + fileName);
                mm.Attachments.Add(new Attachment(file.InputStream, fileName));
            }
        }
        mm.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('Email sent.');"true);
    }
}
VB.Net
Protected Sub SendEmail(sender As Object, e As EventArgs)
    Dim [to] As String = txtTo.Text
    Dim from As String = txtEmail.Text
    Dim subject As String = txtSubject.Text
    Dim body As String = txtBody.Text
    Using mm As New MailMessage(txtEmail.Text, txtTo.Text)
        mm.Subject = txtSubject.Text
        mm.Body = txtBody.Text
        If fuAttachment.HasFile Then
            For Each file As HttpPostedFile In fuAttachment.PostedFiles
                Dim fileName As String = Path.GetFileName(file.FileName)
                file.SaveAs(Server.MapPath("~/Uploads/") & fileName)
                mm.Attachments.Add(New Attachment(file.InputStream, fileName))
            Next
        EndIf
        mm.IsBodyHtml = False
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential(txtEmail.Text, txtPassword.Text)
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        smtp.Send(mm)
        ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('Email sent.');"True)
    End Using
End Sub
Screenshot
The Form displaying Success message

Không có nhận xét nào

Được tạo bởi Blogger.