[英]How do I add an attachment to an email using System.Net.Mail?
我有一個表示為 byte[] 的 excel 文檔,我想將它作為電子郵件中的附件發送。
我在構建附件時遇到了一些麻煩。
我可以創建一個具有以下構造函數的附件:
(Stream contentStream, ContentType contentType)
(Stream contentStream, string name)
(Stream contentStream, string name, string mediaType)
我目前的想法是從 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);
}
就我而言,這只是意味着我必須更改我的方法以將文件名和文件格式作為字符串。 我將嘗試使用 Octet 一個...但如果失敗,我將只傳遞官方 MIME 類型。
考慮到所有因素,這是一個非常明顯的解決方案......但我確實很感激解決它的幫助......好消息是這個解決方案將為未來遇到相同問題的程序員記錄。
再次感謝大家的幫助!
附件構造函數確實有一個構造函數可以滿足您的需要。 我假設您正在使用 .NET Framework 2 中的 System.Net.MailMessage 類。如果是這樣,請閱讀此鏈接以獲取您需要的一些示例代碼
由於已接受答案的鏈接已消失,因此它來自Wayback Machine
TL; DR: 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;
}
從 Microsoft 文檔中得到了這個答案:
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();
}
--------------- 我猜我錯了,這是如果您有要附加的文件 ---------------
看起來這里有一個發送帶有附件的郵件的例子:
http://www.aspnettutorials.com/tutorials/email/email-attach-aspnet2-csharp.aspx
我希望這就是你要找的。
Attachment 構造函數中的 name 參數是將在收件人電子郵件中為附件顯示的名稱。
這樣就可以自由選擇name參數(擴展名.xls首選),將mediaType參數設置為“application/vnd.ms-excel”,這是excel文件定義的MIME類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.