C# .NET - How to attach a file or document - Asked By Daniel on 08-Nov-11 11:58 PM

Hi!How to attach a file or document suchb as word,pdf,notepad etc...I need code for that!
Suchit shah replied to Daniel on 09-Nov-11 12:08 AM
If you upload your file to server. Just use Server.MapPath to get the file on server and then use the MailAttachment to attach the file to MailMassage object.

If you have some issue of getting file from directory. You can use http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx and http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx to find and manipulate file on server.

http://csharp.net-tutorials.com/file-handling/file-and-directory-information/



* Beginning of Attachment1 process & Check the first open file dialog for a attachment */
if (inpAttachment1.PostedFile != null)
{
/* Get a reference to PostedFile object */
HttpPostedFile attFile = inpAttachment1.PostedFile;
/* Get size of the file */
int attachFileLength = attFile.ContentLength;
/* Make sure the size of the file is > 0 */
if (attachFileLength > 0)
{
/* Get the file name */
strFileName = Path.GetFileName(inpAttachment1.PostedFile.FileName);
/* Save the file on the server */   
inpAttachment1.PostedFile.SaveAs(Server.MapPath(strFileName)); 
/* Create the email attachment with the uploaded file */
MailAttachment attach = new MailAttachment(Server.MapPath(strFileName));
/* Attach the newly created email attachment */   
mailMessage.Attachments.Add(attach);
/* Store the attach filename so we can delete it later */
attach1 = strFileName;
}
}
http://asp.net-tutorials.com/controls/file-upload-control/
http://www.c-sharpcorner.com/uploadfile/mahesh/fileupload10092005172118pm/fileupload.aspx
Jitendra Faye replied to Daniel on 09-Nov-11 12:25 AM

Use FileUpload control to upload a file

<form id=

"form1" runat="server">

<asp:FileUpload id="FileUploadControl" runat="server" />

<asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" />

<br /><br />

<asp:

Label runat="server" id="StatusLabel" text="Upload status: " />

</form>

 

In the button click write

this code

protected

void UploadButton_Click(object sender, EventArgs e)

{


if(FileUploadControl.HasFile)

{


try

{


string filename = Path.GetFileName(FileUploadControl.FileName);

FileUploadControl.SaveAs(Server.MapPath("~/") + filename);

StatusLabel.Text = "Upload status: File uploaded!";

}


catch(Exception ex)

{

StatusLabel.Text =

"Upload status: The file could not be uploaded. The following error occured: " + ex.Message;

}

}

}

Try this and let me know.

Riley K replied to Daniel on 09-Nov-11 12:25 AM


Do you mean while sending email ??

Frist take a fileupload control

<asp:FileUpload ID="AttachmentFile" runat="server" />


Follow these steps

'Make sure a file has been uploaded
If String.IsNullOrEmpty(AttachmentFile.FileName) OrElse AttachmentFile.PostedFile Is Nothing Then
  Throw New ApplicationException("Egad, a file wasn't uploaded... you should probably use more graceful error handling than this, though...")
End If
 
'(1) Create the MailMessage instance
Dim mm As New MailMessage(FromEmailAddress, ToEmailAddress)
 
'(2) Assign the MailMessage's properties
mm.Subject = "Emailing an Uploaded File as an Attachment Demo"
mm.Body = Body.Text
mm.IsBodyHtml = False
 
'Attach the file
mm.Attachments.Add(New Attachment(AttachmentFile.PostedFile.InputStream, AttachmentFile.FileName))
 
 
'(3) Create the SmtpClient object
Dim smtp As New SmtpClient
 
'(4) Send the MailMessage (will use the Web.config settings)
smtp.Send(mm)


Regards
Daniel replied to Riley K on 09-Nov-11 12:31 AM
I mean file from my directory then send it to someone to his email account!!
Anoop S replied to Daniel on 09-Nov-11 03:24 AM
Here is a simple example of sending an email in C# with an attachment

public static void CreateMessageWithAttachment(string server, string file)
{
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
       "jane@contoso.com",
       "ben@contoso.com",
       "Quarterly data report.",
       "See the attached spreadsheet.");

    // Create  the file attachment for this e-mail message.
    Attachment attach = new Attachment(file);
    // Add the file attachment to this e-mail message.
    message.Attachments.Add(attach);
    //Send the message.
    SmtpClient client = new SmtpClient(server);
    // Add credentials if the SMTP server requires them.
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
    client.Send(message);
}
kalpana aparnathi replied to Daniel on 09-Nov-11 02:12 PM
Try this code:

please firstly download EAsendmail.dll from the internet
 
using System;
using System.Collections.Generic;
using System.Text;
using EASendMail; //add EASendMail namespace
 
namespace mysendemail
{
  class Program
  {
    static void Main(string[] args)
    {
      SmtpMail oMail = new SmtpMail("TryIt");
      SmtpClient oSmtp = new SmtpClient();
     
      //Set sender email address, please change it to yours
      oMail.From = "test@emailarchitect.net";
      //Set recipient email address, please change it to yours
      oMail.To = "support@emailarchitect.net";
      //Set email subject
      oMail.Subject = "test html email with attachment";
      //Set Html email body
      oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";
 
      //Your smtp server address
      SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
      //User and password for ESMTP authentication, if your server doesn't require
      //User authentication, please remove the following codes.       
      oServer.User = "test@emailarchitect.net";
      oServer.Password = "testpassword";
 
      //If your smtp server requires SSL connection, please add this line
      //oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
 
      try
      {
        //adds attachment from local disk
        oMail.AddAttachment( "d:\\test.pdf" );
         
        //adds attachment from remote website
        oMail.AddAttachment( "http://www.emailarchitect.net/webapp/img/logo.jpg" );
 
        Console.WriteLine("start to send email with attachment ...");
        oSmtp.SendMail(oServer, oMail);
        Console.WriteLine("email was sent successfully!");
      }
      catch (Exception ep)
      {
        Console.WriteLine("failed to send email with the following error:");
        Console.WriteLine(ep.Message);
      }
    }
  }
}