Search code examples
c#.net.net-coreemail-attachments

How to send a generated pdf attachment with email .net-core


I am trying to send a pdf as an attachment via email but the file being sent is corrupt. What might be causing this please? I have provided the code i am using below, I am using the iText7 library.

byte[] file = _pdfCreator.GeneratePdf(transactionDetails);
SendMail.SendEmail("xxxx@gmail.com", "test", "Please find attached", file);

This is to generate the pdf

public byte[] GeneratePdf(List<TransactionDetail> trnx)
        {
            
            using (MemoryStream stream = new MemoryStream())

            {
                
                PdfWriter writer = new PdfWriter(stream);
                PdfDocument pdf = new PdfDocument(writer);
                pdf.AddNewPage();
                Document document = new Document(pdf);
                Paragraph header = new Paragraph("Account Statement")
                   .SetTextAlignment(TextAlignment.CENTER)
                   .SetFontSize(20);

                document.Add(header);
                LineSeparator ls = new LineSeparator(new SolidLine());
                document.Add(ls);
                // New line
                Paragraph newline = new Paragraph(new Text("\n"));

                document.Add(newline);
                Paragraph accountName = new Paragraph("paragraph");
                Paragraph accountNumber = new Paragraph("paragraph");
                Paragraph accountType = new Paragraph("paragraph");
                document.Add(accountName);
                document.Add(accountNumber);
                document.Add(accountType);
                document.Add(newline);

                float[] pointColumnWidths = { 150F, 150F, 150F, 150F, 150F };
                Table table = new Table(pointColumnWidths);
                table.AddCell(new Cell().Add(new Paragraph("Date")));
                table.AddCell(new Cell().Add(new Paragraph("Value")));
                table.AddCell(new Cell().Add(new Paragraph("Description")));
                table.AddCell(new Cell().Add(new Paragraph("Type")));
                table.AddCell(new Cell().Add(new Paragraph("Reference")));

                foreach (var t in trnx)
                {
                    table.AddCell(new Cell().Add(new Paragraph(t.Date.ToString())));
                    table.AddCell(new Cell().Add(new Paragraph(t.Value.ToString())));
                    table.AddCell(new Cell().Add(new Paragraph(t.Descr)));
                    table.AddCell(new Cell().Add(new Paragraph(t.Type.ToString())));
                    table.AddCell(new Cell().Add(new Paragraph(t.Reference)));
                }

                document.Add(table);

                stream.Position = 0;
                document.Close();
                
                stream.Close();

                return stream.ToArray();
               
                
            }
        }
     
    }

This sends the email

public static void SendEmail(string to, string subject, string body, byte[] document)
        {

          
            var attachment = new Attachment(new MemoryStream(document), "statement.pdf", "application/pdf");
            var from = "noreply@xxxxxx.xx";
            string smtpClient = "smtp.xxxxx.xx";
            int port = 2525;
            string username = "xxxxxx";
            string password = "xxxxxx";
            MailMessage mailMessage = new MailMessage();
            mailMessage.To.Add(new MailAddress(to));
            mailMessage.Subject = subject;
            mailMessage.Body = body;
            mailMessage.From = new MailAddress(from);
            mailMessage.IsBodyHtml = false;
            Attachment data = attachment;
            mailMessage.Attachments.Add(data);

            SmtpClient smtp = new SmtpClient(smtpClient)
            {
                Host = smtpClient,
                Port = port,
                UseDefaultCredentials = false,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new System.Net.NetworkCredential(username, password)
            };
            try
            {
                smtp.Send(mailMessage);
            }
            catch (Exception e)
            {
                
            }

I am trying to send a pdf as an attachment via email but the file being sent is corrupt. What might be causing this please? I have provided the code i am using below, I am using the iText7 library.


Solution

  • In your code that generates the PDF, remove (or comment out) stream.close();

        ...
    
    stream.Position = 0;
    document.Close();
                    
    //stream.Close();
    
    return stream.ToArray();
    
        ...