目前我刚刚创建了一个可以发送.xls文件的程序,我使用了谷歌smtp服务器,所以我已经可以在我的程序中使用该服务器发送电子邮件。在我的程序中,根据我的日期,我可以创建.xls包含今天日期和时间的文件。我想知道的是,此文件将用作电子邮件的附件。我该怎么做?
目前我的文件名是DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls"
,因此我可以根据今天的日期和时间进行创建。如何检索要用作电子邮件附件的文件名?
我假设您正在使用.NET 的默认 Emal api 在 System.Net.Mail
命名空间中找到。
您可以将文件作为附件添加到System.Net.Mail.MailMessage
对象。
System.Net.Mail.Attachment
类接受一个构造函数,该构造函数可以获取可用于创建 xls 文件的流。因此,如果您动态创建 excel 文件,您可能已经具有对写入该文件的流的引用。然后你需要使用以下代码:
using (Stream myXlsFileStream = new MemoryStream())
{
// assumig you populate the stream like this...
WriteXlsToStream(myXlsFileStream);
myXlsFileStream.Flush();
MailMessage message = new MailMessage();
// configure mail message contents ...
using (Attachment xlsAttachment = new Attachment(
myXlsFileStream,
"FileNameToAppearInEmail.xls",
"application/xls"))
{
message.Attachments.Add(xlsAttachment);
// send the message
}
}
请注意,流不得关闭,所有数据都应写入其中。在添加附件之前,您可能需要调用myXlsFileStream.Flush()
(如上面的代码所示),以确保文件完全写入。