0

I want to add an attachment to use as a header image in an email. But when I try to attach the file the path is reading from windows and not from my solution directory location. How do I do that?

 var msg = new MailMessage(fromMailAdress, toEmail) { Subject = subject, Body = emailBody };
            msg.Attachments.Add(new Attachment("../images/logo.jpg"));

reads from c:\windows\system32\images\logo.jpg'

I want it from the solution level project/images/logo.jpg

galdin
  • 12,411
  • 7
  • 56
  • 71
Charles Morrison
  • 418
  • 1
  • 4
  • 23
  • You might think this is what you want, but its probably not. Think about what'll happen when you go to deploy your application. – Icemanind Oct 06 '14 at 21:21
  • can you not use a resource file location instead..? here is the MSDN documentation on MailMessage Attachment Header http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.headers(v=vs.110).aspx – MethodMan Oct 06 '14 at 21:24

2 Answers2

1

Here's what you'll want to do:

  1. Create a folder (say attachment) in your solution to store your attachment files.
  2. Use ~/attachment/filename to access the file.

Since ~/attachment/filename is a virtual path, you'll have to convert it to a physical path using Control.ResolveUrl() or a more appropriate way. Check this out for more on it: ResolveUrl without an ASP.NET Page

Community
  • 1
  • 1
galdin
  • 12,411
  • 7
  • 56
  • 71
0

I don't think you mentioned what type of solution you're doing this from.

In a traditional Windows app, you have a few options. You can make sure the logo file is copied to your output directory by right-clicking on it in the project explorer, choosing Properties, and setting the "Copy to Output Directory" feature to "Copy if newer". You will then need to modify your code above to load the image from the executing assembly's path...it's been my experience that Visual Studio will create the "images" project folder.

string logopath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images/logo.jpg");

A better option, as described by DJ KRAZE, is to add your logo as a resource. If you add it to your project as a resource, then you can write it to a temporary file when it doesn't exist. Then, attach it using the path that you created for the temporary file. You can then delete it when you're done, or keep it around and only recreate it when it doesn't exist.

The third option is to upload the logo to a website and then reference it in your email message by the URL, instead of including it as an attachment. If you are creating a HTML mail message, this is probably the best solution.

Markus
  • 761
  • 3
  • 6