Attach File to MailMessage without Saving to Server

时间:2015-07-28 16:21:22

标签: c# email attachment filepicker

I'm having difficulty attaching files to mail messages using C# MailMessage. I have searched on this at length and tried many things that I have come across. The current incarnation is:

string uploadFile1 = fulAttachment1.FileName;
MyMessage.Attachments.Add(
    new Attachment(fulAttachment1.PostedFile.InputStream, uploadFile1));

Where fulAttachment1 is the file picker control.

The errors I keep getting start out like this:

System.IO.FileNotFoundException: Could not find file 'C:\Windows\SysWOW64\inetsrv\neptun-300x299.jpg'

I don't understand why it's looking on the file system at all.

I should add that many of the techniques I have tried work in Visual Studio 2012 and when deployed to IIS on my development machine. The problems arise when it is deployed to IIS on the Internet host. They say there is no problem with the sites configuration, and I don't know enough about it to say otherwise.

Here's the rest of the error message:

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName, String mediaType) at System.Net.Mail.AttachmentBase..ctor(String fileName) at System.Net.Mail.Attachment..ctor(String fileName) at RSG.Webforms.Contact.btnSubmit_Click(Object sender, EventArgs e) in c:\Users\suser\Documents\Visual Studio 2012\Projects\RSA\Webforms\Contact.aspx.cs:line 40

Another thing I don't understand is why IIS on a remote server would refer to my local Visual Studio project

1 个答案:

答案 0 :(得分:2)

如评论中所述fuAttachment1.FileName引用文件名;你必须改为访问文件字节流。

string uploadFile1 = System.IO.Path.GetFileName(fulAttachment1.FileName);
MyMessage.Attachments.Add(new Attachment(fulAttachment1.FileContent, uploadFile1)));

参考文献:

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload_properties(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.net.mail.attachment.attachment(v=vs.110).aspx