Friday, October 14, 2011

Send Mail with attachment in ASP.Net

Use below code for sending mail with attachment:

            SmtpClient smtpClient = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential("UserName", "Password");
            smtpClient.Host = "SMTP Server";
            smtpClient.Port = 25;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = basicCredential;

            MailMessage message = new MailMessage();
            message.From = new MailAddress("Sender mail address");

            String[] ToAddress = TextBox1.Text.Split(','); //TextBox1 contains Receiver Mail addresses separated by comma
            for (int i = 0; i < ToAddress.Length;i++)
                message.To.Add(new MailAddress(ToAddress[i]));
          
            message.Subject = TextBox3.Text;
            message.IsBodyHtml = true;
            message.Body = TextBox2.Value;

            //----------------------------1 (Attachment: Data Text File where Data Fetching From database)
            //Get some binary data
            //byte[] data = GetDatabaseData();//User Defined Function
            ////save the data to a memory stream
            //System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
            ////create the attachment from a stream. Be sure to name the data with a file and
            ////media type that is respective of the data
            //message.Attachments.Add(new Attachment(ms, "example.txt", "text/plain"));
            //Should be Dispose/close MemoryStream 'ms' after sending the mail


            //----------------------------2 (Attachment: Excel File Which is already exist in the server)
            // Specify the file to be attached and sent. This example assumes that a file named Data.xls exists in the current working directory.
            //string file = "data.xls";
            //// Create  the file attachment for this e-mail message.
            //Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            //// Add time stamp information for the file.
            //ContentDisposition disposition = data.ContentDisposition;
            //disposition.CreationDate = System.IO.File.GetCreationTime(file);
            //disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            //disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            //// Add the file attachment to this e-mail message.
            //message.Attachments.Add(data);
            //Should be Dispose 'data' file after sending the mail


            //---------------------------3 (Attachment: Client attached the file)
            // Check to see if file was attached
            if (File1.PostedFile != null)
            {
                // Get a reference to PostedFile object
                HttpPostedFile myFile = File1.PostedFile;
                // Get size of uploaded file
                int nFileLen = myFile.ContentLength;
                // make sure the size of the file is > 0
                // Allocate a buffer for reading of the file
                byte[] myData = new byte[nFileLen];
                // Read uploaded file from the Stream
                myFile.InputStream.Read(myData, 0, nFileLen);
                //save the data to a memory stream
                System.IO.MemoryStream ms = new System.IO.MemoryStream(myData);
                //create the attachment from a stream. Be sure to name the data with a file and
                //media type that is respective of the data
                String extension = System.IO.Path.GetExtension(myFile.FileName);
                if (extension == ".exe")
                {
                    Label1.Text = "Execution File Not Allowed";
                    return;
                }
                else if (extension == ".pdf")
                    message.Attachments.Add(new Attachment(ms, myFile.FileName,               System.Net.Mime.MediaTypeNames.Application.Pdf));
                else if (extension == ".zip")
                    message.Attachments.Add(new Attachment(ms, myFile.FileName, System.Net.Mime.MediaTypeNames.Application.Zip));
                else
                    message.Attachments.Add(new Attachment(ms, myFile.FileName, System.Net.Mime.MediaTypeNames.Application.Octet));
            }

            try
            {
                smtpClient.Send(message);
                Label1.Text = "Successfully Sent";
            }
            catch (Exception ex)
            {
                //Error, could not send the message
                Label1.Text = ex.Message;
            }

No comments:

Post a Comment