How to Send the Runtime Generated File as Attachment in Sending Mail Using C#

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:

  • Create a new website.
  • Add a reference of the downloaded "iTextSharp.dll" to the Website
  • Add a page into the website and add 3 textboxes into the page for the receiver Email-ID, subject of Email and message of Email and a button for sending the mail.
  • Write some code in the ".cs" file to send the mail with some Text and runtime generated file on the button click event.

The following are the details of the preceding procedure.

Step 1

  • Create a new empty Website named "MailServer".



  • Right-click on the website and click on "Add Reference…".



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

    • Add a new Page named "SendingMail.aspx".



    • Add a Button with Onclick event (for sending the Email) to the page.
      1. <table>  
      2.             <tr>  
      3.                 <td>Mail To:-</td>  
      4.                 <td>  
      5.                     <asp:TextBox ID="txtEmail" runat="server" Width="200px">  
      6.                     </asp:TextBox></td>  
      7.             </tr>  
      8.             <tr>  
      9.                 <td>Subject:-</td>  
      10.                 <td>  
      11.                     <asp:TextBox ID="txtSubject" runat="server" Width="200px">  
      12.                     </asp:TextBox></td>  
      13.             </tr>  
      14.             <tr>  
      15.                 <td>Message:-</td>  
      16.                 <td>  
      17.                     <asp:TextBox ID="txtmessagebody" runat="server" TextMode="MultiLine" Height="200px" Width="400px">  
      18.                     </asp:TextBox></td>  
      19.             </tr>  
      20.             <tr>  
      21.                 <td colspan="2" align="center">  
      22.                     <asp:Button ID="btn_send" runat="server" Text="Send Mail"  
      23.                         OnClick="btn_send_Click" /></td>  
      24.             </tr>  
      25.         </table>  



    • Add the following 6 namespaces to the top of the ".cs" file.
      1. using System.Net.Mail;  
      2. using System.IO;  
      3. using System.Text;  
      4. using System.Net.Mime;  
      5. using iTextSharp.text;  
      6. using iTextSharp.text.pdf;  
    • Write the code to send the Email on the click event of the button.
      1. protected void btn_send_Click(object sender, EventArgs e)  
      2.  {  
      3.      try  
      4.      {  
      5.          MailMessage message = new MailMessage();  
      6.          message.To.Add(txtEmail.Text);// Email-ID of Receiver  
      7.          message.Subject = txtSubject.Text;// Subject of Email  
      8.          message.From = new System.Net.Mail.MailAddress("no-reply@test.com");// Email-ID of Sender  
      9.          message.IsBodyHtml = true;  
      10.   
      11.          MemoryStream file = new MemoryStream(PDFGenerate("This is pdf file text", Server.MapPath("Images/photo.jpg")).ToArray());  
      12.   
      13.          file.Seek(0, SeekOrigin.Begin);  
      14.          Attachment data = new Attachment(file, "RunTime_Attachment.pdf""application/pdf");  
      15.          ContentDisposition disposition = data.ContentDisposition;  
      16.          disposition.CreationDate = System.DateTime.Now;  
      17.          disposition.ModificationDate = System.DateTime.Now;  
      18.          disposition.DispositionType = DispositionTypeNames.Attachment;  
      19.          message.Attachments.Add(data);//Attach the file  
      20.   
      21.          message.Body = txtmessagebody.Text;  
      22.          SmtpClient SmtpMail = new SmtpClient();  
      23.          SmtpMail.Host = "Your Host";//name or IP-Address of Host used for SMTP transactions  
      24.          SmtpMail.Port = 25;//Port for sending the mail  
      25.          SmtpMail.Credentials = new System.Net.NetworkCredential("""");//username/password of network, if apply  
      26.          SmtpMail.DeliveryMethod = SmtpDeliveryMethod.Network;  
      27.          SmtpMail.EnableSsl = false;  
      28.          SmtpMail.ServicePoint.MaxIdleTime = 0;  
      29.          SmtpMail.ServicePoint.SetTcpKeepAlive(true, 2000, 2000);  
      30.          message.BodyEncoding = Encoding.Default;  
      31.          message.Priority = MailPriority.High;  
      32.          SmtpMail.Send(message); //Smtpclient to send the mail message  
      33.          Response.Write("Email has been sent");  
      34.      }  
      35.      catch (Exception ex)  
      36.      { Response.Write("Failed"); }  
      37.  }  

    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.   
    4.         MemoryStream output = new MemoryStream();  
    5.   
    6.         Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);  
    7.         PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, output);  
    8.   
    9.         pdfDoc.Open();  
    10.         Paragraph Text = new Paragraph(message);  
    11.         pdfDoc.Add(Text);  
    12.   
    13.         byte[] file;  
    14.         file = System.IO.File.ReadAllBytes(ImagePath);  
    15.   
    16.         iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(file);  
    17.         jpg.ScaleToFit(550F, 200F);  
    18.         pdfDoc.Add(jpg);  
    19.   
    20.         pdfWriter.CloseStream = false;  
    21.         pdfDoc.Close();  
    22.         output.Position = 0;  
    23.   
    24.         return output;  
    25.     }     



    Step 4

     

    • Run the Page on the server that will be like:



    • After filling in the valid Email ID, Subject of Email and message of the Email, click on the "Send mail" button for sending the email.




    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.