Introduction

This article describes how to send an email with a runtime generated file as an attachment in C#. For sending the email, you need to configure the email services on the server.

Note 1: For more info about configuration read the article about how to configure the mail server (http://technet.microsoft.com/en-us/library/cc780996%28v=ws.10%29.aspx)

Note 2: I will use the "iTextSharp.dll" as a PDF generator library.

You can download it from the following.

  1. Links

    http://sourceforge.net/projects/itextsharp
    https://www.nuget.org/packages/iTextSharp/

    Or you can download the attached file of this article.

To explain this article, I will use the following procedure after configuring the server:

The following are the details of the preceding procedure.

Step 1

Use the following sub-steps in the "Reference Manager":
  1. Click on the Browse tab on the left side
  2. Click on the Browse button at the bottom
  3. Select the "iTextSharp.dll" from the system
  4. Click on the Add button


Finally it will look like:



Now click on the "OK" button and see the "Solution Explorer" where the "iTextSharp.dll" reference has been added to the "Bin" folder.



Step 2

Note: The "SmtpMail.Host" value will be your hosting name or IP Address and "SmtpMail.Port" will also vary.

  1. private MemoryStream PDFGenerate(string message, string ImagePath)
  2. {
  3. MemoryStream output = new MemoryStream();
  4. Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
  5. PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, output);
  6. pdfDoc.Open();
  7. Paragraph Text = new Paragraph(message);
  8. pdfDoc.Add(Text);
  9. byte[] file;
  10. file = System.IO.File.ReadAllBytes(ImagePath);
  11. iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(file);
  12. jpg.ScaleToFit(550F, 200F);
  13. pdfDoc.Add(jpg);
  14. pdfWriter.CloseStream = false;
  15. pdfDoc.Close();
  16. output.Position = 0;
  17. return output;
  18. }


Step 4

Result: Now you can see that, I (the receiver) got the email.



After downloading the file see the text and image in the .pdf file.