我正在编写一个程序将文件附加到电子邮件。目前,我正在将使用的文件保存FileStream到磁盘中,然后使用
FileStream
System.Net.Mail.MailMessage.Attachments.Add( new System.Net.Mail.Attachment("file name"));
我不想将文件存储在磁盘中,我想将文件存储在内存中,然后从内存流中将其传递给Attachment。
Attachment
这是示例代码。
System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.StreamWriter writer = new System.IO.StreamWriter(ms); writer.Write("Hello its my sample file"); writer.Flush(); writer.Dispose(); ms.Position = 0; System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct); attach.ContentDisposition.FileName = "myFile.txt"; // I guess you know how to send email with an attachment // after sending email ms.Close();
编辑1
您可以通过System.Net.Mime.MimeTypeNames指定其他文件类型,例如 System.Net.Mime.MediaTypeNames.Application.Pdf
System.Net.Mime.MediaTypeNames.Application.Pdf
根据 Mime类型, 您需要在FileName中指定实例扩展名"myFile.pdf"
"myFile.pdf"