在ASP.NET中以编程方式发送带附件的邮件
我基于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类发送邮件……如果可能的话!
您可以从字符串创建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);
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); }
您可以将文件内容保存为字节数组,然后执行以下操作:
创建内存中的邮件附件
这是我之前提到的一个工作示例,代码中有一些额外的逻辑将GridView解析为Table。
上述就是C#学习教程:在ASP.NET中以编程方式发送带附件的邮件分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
//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); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1042101.html