C# 如何使用System.Net.Mail向电子邮件添加附件?
我有一个excel文档,以字节[]表示,我想将其作为电子邮件附件发送 我在构建附件方面有点困难 我可以创建包含以下构造函数的附件:C# 如何使用System.Net.Mail向电子邮件添加附件?,c#,email,binary,attachment,system.net.mail,C#,Email,Binary,Attachment,System.net.mail,我有一个excel文档,以字节[]表示,我想将其作为电子邮件附件发送 我在构建附件方面有点困难 我可以创建包含以下构造函数的附件: (Stream contentStream, ContentType contentType) (Stream contentStream, string name) (Stream contentStream, string name, string mediaType) 我现在的想法是从字节[]创建一个MemoryStream,并将其传递给创建附件的方法 不幸
(Stream contentStream, ContentType contentType)
(Stream contentStream, string name)
(Stream contentStream, string name, string mediaType)
我现在的想法是从字节[]创建一个MemoryStream,并将其传递给创建附件的方法
不幸的是,我看不到从MemoryStream获得预期文件名和内容类型的方法,也看不到如何提供正确的内容类型。有纯文本、Pdf、Rtf等选项,但我看不到任何一个选项可以立即跳出我的视线,作为我应该用于Excel文档的选项
我能找到的最接近的状态是:
八位字节成员指定
附件包含通用二进制文件
数据
然而,即使这是要使用的,除非它可以作为流的属性传递,否则我发送电子邮件的方法将只能发送一个字节[]作为Excel文档
是否有其他类型的溪流可以使用?或者,我必须创建自己的流类型,其中包含我需要的详细信息
肯定有人以前做过这件事,微软肯定会把这件事考虑到这个程度
任何帮助都将不胜感激
更新:
请不要投票支持任何使用将文件名作为字符串的构造函数的答案。我真的需要帮助使用的那些采取流…我想避免写文件到磁盘,电子邮件,然后立即删除它。因为有一种方法可以让我做到这一点,如果可能的话,我愿意使用这种方法
解决方案更新
康拉德设法找到了我要找的东西!谢谢你,伙计
我将记录建议的解决方案,以防在提供的链接中的内容发生问题
这一解决方案的功劳在于
在我的例子中,这只是意味着我必须改变我的方法,将文件名和文件格式作为字符串。我会尝试使用八位组一…但如果失败,我只会传递正式的MIME类型
从各方面考虑,这是一个非常明显的解决方案…但我非常感谢在解决它方面的帮助…好的是,这个解决方案将被记录下来,供未来有同样问题的程序员使用
再次感谢大家的帮助 ------我想我错了,这是你想要附加的文件---------------
这里似乎有一个发送带有附件的邮件的示例:
我希望这就是您要查找的内容。附件构造函数中的name参数是将在收件人电子邮件中为附件显示的名称
因此,您可以自由选择name参数(首选扩展名.xls),并将mediaType参数设置为“application/vnd.ms excel”,这是为excel文件定义的参数。附件构造函数确实有一个满足您需要的构造函数。我假设您使用的是.Net Framework 2中的System.Net.MailMessage类。如果您需要的一些示例代码是这样的,因为来自的已不存在,这里是来自 TL;DR:
mail.Attachments.Add(新附件(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;
}
从Microsoft docs获得以下答案:
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane@contoso.com",
"ben@contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this email message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this email message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
ex.ToString());
}
// Display the values in the ContentDisposition for the attachment.
ContentDisposition cd = data.ContentDisposition;
Console.WriteLine("Content disposition");
Console.WriteLine(cd.ToString());
Console.WriteLine("File {0}", cd.FileName);
Console.WriteLine("Size {0}", cd.Size);
Console.WriteLine("Creation {0}", cd.CreationDate);
Console.WriteLine("Modification {0}", cd.ModificationDate);
Console.WriteLine("Read {0}", cd.ReadDate);
Console.WriteLine("Inline {0}", cd.Inline);
Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
foreach (DictionaryEntry d in cd.Parameters)
{
Console.WriteLine("{0} = {1}", d.Key, d.Value);
}
data.Dispose();
}
不幸的是,这并不是因为该示例中使用的方法是传递一个文件名字符串…这意味着文件必须在发送之前写入磁盘。我想在内存中完成这一切,因为我没有理由将文件写入磁盘,发送它,然后删除文件..很抱歉否决你的答案John,但有人否决了它,它不是正确的答案。请,没有其他人投票给这个答案…我需要创建附件使用的构造函数,采取流不是字符串。谢谢!这正是我想要的。你是怎么找到的?我想我们都用同一个谷歌搜索?哈哈!好吧,我们就说在我的工作过程中,我花了很多时间寻找问题的答案!感谢Rad,这是一个非常方便的链接,在该链接中没有提到,但是请确保您可以使用您的附件(处理底层流),或者调用mail.Dispose()
,它可以为您执行此操作。链接已失效。转载万岁!
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane@contoso.com",
"ben@contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this email message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this email message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
ex.ToString());
}
// Display the values in the ContentDisposition for the attachment.
ContentDisposition cd = data.ContentDisposition;
Console.WriteLine("Content disposition");
Console.WriteLine(cd.ToString());
Console.WriteLine("File {0}", cd.FileName);
Console.WriteLine("Size {0}", cd.Size);
Console.WriteLine("Creation {0}", cd.CreationDate);
Console.WriteLine("Modification {0}", cd.ModificationDate);
Console.WriteLine("Read {0}", cd.ReadDate);
Console.WriteLine("Inline {0}", cd.Inline);
Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
foreach (DictionaryEntry d in cd.Parameters)
{
Console.WriteLine("{0} = {1}", d.Key, d.Value);
}
data.Dispose();
}