Friday, February 11, 2011

How to send a email with multiple attachments using Aspnet

Hi friends In this article i would like to explain how to send a email with multiple attachments
First,Open the Microsoft Visual Studio 2008
Next,Select a Aspnet web application and change the name as SendingEmail
Next,Open the Design Page of Default.aspx

Next,Drag and drop the controls from the tool box and arrange the controls as shown in the below figure

Next,Open the Source Page of Default.aspx

and write the javascript for Add Button


<input id="AddFile" type="button" value="Add file" onclick="addmore()" />

<script type="text/javascript">  

     function addmore()
      {  
         if (!document.getElementById || !document.createElement)  
             return false;  
   
         var uploadArea = document.getElementById("upload-area");  
   
         if (!uploadArea)  
             return;  
   
         var newLine = document.createElement("br");  
         uploadArea.appendChild(newLine);  
   
         var newUploadBox = document.createElement("input");  
   
          
         newUploadBox.type = "file";  
         newUploadBox.size = "60";  
   
          
         if (!addmore.lastAssignedId)  
             addmore.lastAssignedId = 100;  
   
         newUploadBox.setAttribute("id", "dynamic" + addmore.lastAssignedId);  
         newUploadBox.setAttribute("name", "dynamic:" + addmore.lastAssignedId);  
         uploadArea.appendChild(newUploadBox);  
         addmore.lastAssignedId++;  
   }  

function ValidateFileUpload(Source, args)
{
  var fuData = document.getElementById('<%= File1.ClientID %>');
  var FileUploadPath = fuData.value;

  if(FileUploadPath =='')
  {
    
    args.IsValid = false;
  }
  else
  {
    var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

    if (Extension == "xls" || Extension == "xml" || Extension == "doc" || Extension == "txt")
    {
      args.IsValid = true; // Valid file type
    }
    else
    {
      args.IsValid = false; // Not valid file type
    }
   }
}
</script> 
Next,open the Default.aspx.cs page and write the following code in the button event

Here,you have to add System.Net.Mail namespace
protected void btn_send_Click(object sender, EventArgs e)
    {
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

        msg.From = new MailAddress("emailid@gmail.com");

        msg.To.Add(txt_email.Text);//Text Box for To Address

        msg.Subject = txt_name.Text; //Text Box for subject

        msg.IsBodyHtml = true;

        msg.Body = txt_comment.Text;//Text Box for body

        msg.Priority = MailPriority.High;

        HttpFileCollection uploads = HttpContext.Current.Request.Files;
        for (int i = 0; i < uploads.Count; i++)
        {
            HttpPostedFile upload = uploads[i];

            if (upload.ContentLength == 0)
                continue;

            string c = System.IO.Path.GetFileName(upload.FileName);

            try
            {
                msg.Attachments.Add(new Attachment(File1.PostedFile.InputStream, upload.FileName));
               
                Span1.InnerHtml = "Upload(s) Successful.";
            }
            catch (Exception ex)
            {
                Span1.InnerHtml = "Upload(s) FAILED.";
            }
        }



        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);

        client.UseDefaultCredentials = false;

        client.Credentials = new System.Net.NetworkCredential("gmailusername", "gmailpassword");


        client.Port = 587;

        client.Host = "smtp.gmail.com";

        client.EnableSsl = true;

        object userstate = msg;

        client.Send(msg);

        lbl_confirm.Text = "Mail Sent Successfully.";//label for displaying message.
    }
Finally , Open the Web config file and search for <system.net>

and write the following code
<system.net>
    <mailSettings>
      <smtp from="emailid@gmail.com">
        <network host="smtp.gmail.com" password="gmailpassword" port="587"
          userName="gmailuserid" defaultCredentials="true"/>
      </smtp>
    </mailSettings>
  </system.net>
Thats it..If You Have any doubts please feel free to ask me i will always ready to help you can download the entire source code form here 
developercode
About the Author
Sayyad is a Software Engineer, Blogger and Founder of Developers Code from India.His articles mainly focus on .Net (Web and Windows based applications), Mobile Technologies (Android,IPhone,BlackBerry) and SEO.

Labels: , , , , ,

4 Comments:

At April 25, 2011 at 7:52 PM , Anonymous Anonymous said...

Its working........Thanks a lot

 
At April 25, 2011 at 7:52 PM , Anonymous Anonymous said...

Nice code

 
At April 25, 2011 at 7:52 PM , Anonymous lamins said...

Good one...

 
At April 8, 2014 at 4:51 PM , Anonymous SARAT said...

After clicking send button, the mail will send with the attachments. Here, my requirement is delete those attached files after the sending mail. That code should written on send button click event only. Please send that code to my email address which is, csarath19@gmail.com ...

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home