Search code examples
asp.net-mvc-3mimeemail-attachments

Attaching Word Document as an Attachment - Path Specification ASP.NET MVC 3


I need to attach a word document to an email.

The document is being stored in the solution, in a folder called "Attachments"

Question

I was wondering what path i need to use in order to attach a Word document to an email and also would like to know if I am attaching it correctly.

Here is how I am doing it:

string fileName = "~/Attachments/worddocument.doc";
MailMessage mail = new MailMessage
    {
        Sender = new MailAddress(this.SenderAddress, this.SenderName),
        From = new MailAddress(this.FromAddress, this.FromName),
        ReplyToList = { new MailAddress(this.ReplyToAddress, this.ReplyToName) },
        IsBodyHtml = this.isBodyHtml,
        Subject = this.UserSubject,
        Attachments.Add(new Attachment(fileName, MediaTypeNames.Application.Octet));
     };

How does that look? Did I specify the path correctly?

Thanks


Solution

  • Attachment expects an absolute path.

    You can convert your virtual path to an absolute path with

    var absolutePath = Server.MapPath("~/Attachments/worddocument.doc")
    

    And attach it with

    Attachments.Add(new Attachment(absolutePath, MediaTypeNames.Application.Octet));
    

    If you want to check if the file in the virtual directory exists, use

    if (File.Exists(absolutePath))
    ...