[SOLVED] Auto attachment file for email service c# asp.net

Issue

I have generated a PDF file from my gridview. My task is to send the PDF file that I have generated to a specific email without the user to use the upload control and select the PDF file I generated. I am able to do the normal email with the user manually browse and select the PDF as attachment. Is there a way to achieve the auto attachment of a PDF file to the email?

SqlDataSource SqlDataSource1 = new SqlDataSource();
        SqlDataSource1.ID = "SqlDataSource1";
        this.Page.Controls.Add(SqlDataSource1);
        SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        SqlDataSource1.SelectCommand = "SELECT Id, msgContent, msgDate from Message where msgDate between '" + dateFrom + "' and '" + dateTo + "'";
        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();

This my data binding to the gridview.

StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());

        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlworker = new HTMLWorker(pdfDoc);

        using (MemoryStream ObjememoryStream = new MemoryStream())
        {
            PdfWriter.GetInstance(pdfDoc, ObjememoryStream);
            pdfDoc.Open();
            htmlworker.Parse(sr);
            pdfDoc.Close();
            byte[] Filebytes = ObjememoryStream.ToArray();
            ObjememoryStream.Close();
            using (MemoryStream inputData = new MemoryStream(Filebytes))
            {
                using (MemoryStream outputData = new MemoryStream())
                {
                    string PDFFileword = txtPassword.Text;//you can also generate Dynamic word  
                    PdfReader reader = new PdfReader(inputData);
                    PdfEncryptor.Encrypt(reader, outputData, true, PDFFileword, PDFFileword, PdfWriter.ALLOW_SCREENREADERS);
                    Filebytes = outputData.ToArray();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(Filebytes);
                    Response.End();
                    GridView1.AllowPaging = true;
                    GridView1.DataBind();
                }
            }
        }

This is the way I generate the PDF file.

using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
        {
            mm.Subject = txtSubject.Text;
            mm.Body = txtBody.Text;
            if (fuAttachment.HasFile)
            {
                string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
                mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.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(GetType(), "alert", "alert('Email sent.');", true);
        }

This is the way I am sending email by upload control the attachment file. "fuAttachment" is the ID of my upload control, is there a way to make the attachment became automatically?

Solution

You just need to create new Attachment instance and add it to the collection of attatchments in mailmessage instance like this.

if you have file physically stored on hard drive and you know the path then:

Attachment attachment = new Attachment("FILE_PATH", 
                     MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);

if you have byte array in memory then:

Stream stream = new MemoryStream(byteArray);
Attachment attachment = new Attachment(stream, MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);

if you have stream then:

Attachment attachment = new Attachment(fileStream, MediaTypeNames.Application.Octet);
mm.Attachments.Add(attachment);

Answered By – Jenish Rabadiya

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *