我基于ASP.NET中的GridView动态生成许多不同类型的文件 - Excel电子表格和HTML文件。我这样做是使用此代码(这仅适用于Excel电子表格):
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=InvoiceSummary" + Request.QueryString["id"] + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
contents.RenderControl(htmlWrite);
//GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
我想向用户提供选项,通过电子邮件将生成的文件作为附件发送给他们指定的电子邮件地址,或者将其与数据库中的帐户相关联。但我不希望用户必须保存文件,然后将其附加到表单中 - 我想自动附加生成的文件。这有可能吗,它有多容易?
当然,我将使用System.Net.Mail类发送邮件......如果可能的话,无论如何!
答案 0 :(得分:8)
您可以从字符串创建System.Net.Mail.Attachment,然后照常发送邮件。
var m = new System.Net.Mail.MailMessage(from, to, subject, body);
var a = System.Net.Mail.Attachment.CreateAttachmentFromString(stringWrite.ToString(), "application/vnd.xls");
m.Attachments.Add(a);
答案 1 :(得分:1)
protected void btnSend_OnClick(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
byte[] data = new byte[1024];
MemoryStream stream = new MemoryStream(data);
Attachment attach = new Attachment(stream, "Attachment file name");
mail.Attachments.Add(attach);
new SmtpClient().Send(mail);
}
答案 2 :(得分:0)
您可以将文件内容保存为字节数组,然后执行以下操作:
答案 3 :(得分:0)
这是我之前提到的一个工作示例,代码中有一些额外的逻辑将GridView解析为表。
//Table to store our GridView Data
Table table = new Table();
//Parse our GridView into Table, stored in a StringBuilder
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// header
if (GridView1.HeaderRow != null)
{
table.Rows.Add(GridView1.HeaderRow);
}
// details
foreach (GridViewRow row in GridView1.Rows)
{
table.Rows.Add(row);
}
// footer
if (GridView1.FooterRow != null)
{
table.Rows.Add(GridView1.FooterRow);
}
// render table
table.RenderControl(htw);
}
}
using (MemoryStream memoryStream = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(memoryStream))
{
//Convert StringBuilder to MemoryStream
writer.Write(sb.ToString());
writer.Flush();
//Create Message
MailMessage message = new MailMessage();
message.To.Add(new MailAddress("you@address.com", "You"));
message.From = new MailAddress("me@address.com", "Me");
message.Subject = "The Subject";
//Create Attachment
Attachment attachment = new Attachment(memoryStream, "InvoiceSummary.xls", "application/vnd.xls");
//Attach Attachment to Email
message.Attachments.Add(attachment);
//Open SMTP connection to server and send
SmtpClient smtp = new SmtpClient();
smtp.Port = 25;
smtp.Send(message);
}
}