Adding an attachment to a .NET Email

拈花ヽ惹草 提交于 2019-12-22 04:26:31

问题


How do I attach a file with a very unfriendly name (like a file with a session Id number in it) but have it attached as another name?

The file name in question has the session ID in it to avoid clashes name on the web server but when I attach it to the file, a friendlier name is preferable.

Is there a way to attach the file with the unfriendly name as another name so that when the user gets the email he can tell from the name what the content of the file is? I'd hate to have to create a unique folder just to put a non unique file name in it for the purpose of simply attaching it to an email.

Dim mailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
mailMessage.Attachments.Add("C:\My\Code\BESI\BESI\Files\Invoice-djopyynrgek4p4qadn31dxxs.pdf", ????)

回答1:


Yeah--you can do what you're trying to do by using a different constructor for Attachment(). Sadly there's not one that takes a filename and a separate name, but there is one that takes a Stream and a separate name. And there are helper methods on System.IO.File that make it easy to get a file stream from a file name.

Imports System.Net.Mail
Imports System.IO

Dim mailMessage as MailMessage = New MailMessage()
Dim stream as FileStream = File.OpenRead("C:\My\Code\BESI\BESI\Files\Invoice-djopyynrgek4p4qadn31dxxs.pdf")
Dim attachment as Attachment = New Attachment(stream, "FriendlyName.pdf")
mailMessage.Attachments.Add(attachment)

'Be sure to Dispose stream after you've sent the mail.

(My VB syntax is weak, so there may be some silly mistakes in there, but hopefully my meaning is clear, and those are definitely the right classes/methods to use.)



来源:https://stackoverflow.com/questions/2570127/adding-an-attachment-to-a-net-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!