我如何设置一个字符串列表的电子邮件附件与httppostdfilebase文件
本文关键字:电子邮件 文件 httppostdfilebase 列表 一个 何设置 设置 字符串 | 更新日期: 2023-09-27 18:05:57
在我的MVC项目我有一个订单表单与两个上传字段。
我试图将上传的文档附加到电子邮件中,但无法正常工作。
我的send email函数需要一个附件列表和一个附件名称列表,如下所示:
public class Email
{
public string To { get; set; }
public string From { get; set; }
public string Body { get; set; }
public string Subject { get; set; }
public string CC { get; set; }
public string Bcc { get; set; }
public List<string> Attachments { get; set; }
public List<string> AttachmentsNames { get; set; }
}
和提交表单的函数:
public ActionResult SubmitOrder(Order order)
{
public OrderViewModel oViewModel = new OrderViewModel();
oViewModel.email = new Email();
oViewModel.email.To = "test@test.test";
oViewModel.email.CC = "test@test.test";
oViewModel.email.Subject = "Order";
oViewModel.email.From = "info@test.com";
oViewModel.email.Bcc = "test@test.test";
oViewModel.email.Body = "<html><body><table border=0>" +
//content of the form
"</table></body></html>";
List<string> attachments = new List<string>(new string[] { order.file1.InputStream });
//I'm getting the error at this point
List<string> attachmentsNames = new List<string>(new string[] { order.file1.FileName});
oViewModel.email.Attachments = attachments;
oViewModel.email.AttachmentsNames = attachmentsNames;
//rest of code that actually send the email
}
正如你所看到的,我尝试了:file1.InputStream
(file1
是httpPostedFileBase
类型),但得到了转换错误:
不能隐式转换System.IO类型。流'到'字符串'
你知道怎么做吗?
将上传的文件保存到磁盘,然后将文件位置传递给电子邮件
//...other code
var attachments = new List<string>();
var attachmentsNames = new List<string>();
var file = order.file1;
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var filePath = Path.Combine(Server.MapPath("~/App_Data/attachments"), fileName);
file.SaveAs(filePath);//save the file to disk
//add file path and name to collections.
attachments.Add(filePath);
attachmentsNames.Add(fileName);
}
//...other code
我也会检查确保上传的文件被删除/删除后,确认电子邮件发送,否则有可能耗尽磁盘空间。
更新:基于注释
考虑到电子邮件部分是你们都使用的自定义代码,我将首先检查发送后是否已经在删除文件这些电子邮件。如果不是,那么在你说
//rest of code that actually send the email
的部分,在发送电子邮件后,你可以简单地遍历附件列表并根据路径删除文件。
//rest of code that actually send the email
foreach(var path in attachments) {
if(File.Exists(path)) File.Delete(path);
}