mez*_*oid 17 c# email binary attachment system.net.mail
我有一个表示为byte []的excel文档,我想将其作为附件发送到电子邮件中.
我在构建附件时遇到了一些麻烦.
我可以创建一个具有以下构造函数的Attachment:
(Stream contentStream, ContentType contentType)
(Stream contentStream, string name)
(Stream contentStream, string name, string mediaType)
Run Code Online (Sandbox Code Playgroud)
我的想法是从byte []创建一个MemoryStream并将其传递给创建附件的方法.
不幸的是,我看不到从MemoryStream获取预期文件名和内容类型的方法,我也看不到如何提供正确的内容类型.有纯文本,Pdf,Rtf等选项,但我没有看到立即跳出来作为我应该用于Excel文档的那个.
我能找到的最接近的是MediaTypeNames.Application.Octet,其中说明:
Octet成员指定附件包含通用二进制数据.
但是,即使这是一个使用的,除非它可以作为Stream的属性传递,那么我的发送电子邮件的方法只能发送一个byte []作为Excel文档...
是否有其他类型的流可以使用?或者我是否必须创建我自己的Stream类型,其中包含我需要的详细信息.
当然有人在那里做过这件事,当然微软会想到这个水平......
任何帮助将非常感激.
更新: 请不要投票使用将文件名作为字符串的构造函数的任何答案.我真的需要帮助使用带有Stream的那些......我想避免将文件写入磁盘,通过电子邮件发送,然后立即将其删除.由于有一种方法可以让我这样做,我想尽可能使用那个.
解决方案更新
康拉德设法找到了我要找的东西!谢谢堆人!
我只是记录建议的解决方案,以防万一在提供的链接上的内容发生了什么.
这个解决方案可以归功于www.systemnetmail.com
static void AttachmentFromStream()
{
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "this content is in the body";
//Get some binary data
byte[] data = GetData();
//save the data to a memory stream
MemoryStream ms = new MemoryStream(data);
//create the attachment from a stream. Be sure to name the data
//with a file and
//media type that is respective of the data
mail.Attachments.Add( new Attachment( ms, "example.txt", "text/plain" ));
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);
}
Run Code Online (Sandbox Code Playgroud)
在我的情况下,它只是意味着我将不得不改变我的方法采取文件名和fileformat作为字符串.我会尝试使用Octet ...但如果没有,我将只传入官方MIME类型.
考虑到所有事情,这是一个非常明显的解决方案......但我非常感谢帮助解决它...好的是这个解决方案将记录给具有相同问题的未来程序员.
再次感谢大家的帮助!
Rad*_*Rad 13
附件构造函数确实有一个构造函数可以满足您的需要.我假设您正在使用.NET Framework 2中的System.Net.MailMessage类.如果是这样,请阅读此链接以获取您需要的示例代码
特尔;博士: mail.Attachments.Add(new Attachment(contentStream, "yourfilename.txt", "text/plain"));
满的:
static void AttachmentFromStream()
{
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "this content is in the body";
//Get some binary data
byte[] data = GetData();
//save the data to a memory stream
MemoryStream ms = new MemoryStream(data);
//create the attachment from a stream. Be sure to name the data with a file and
//media type that is respective of the data
mail.Attachments.Add(new Attachment(ms, "example.txt", "text/plain"));
//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);
}
static byte[] GetData()
{
//this method just returns some binary data.
//it could come from anywhere, such as Sql Server
string s = "this is some text";
byte[] data = Encoding.ASCII.GetBytes(s);
return data;
}
Run Code Online (Sandbox Code Playgroud)