如何使用 httpPostedFileBase 文件设置电子邮件附件的字符串列表?

How do I set a string list of email attachments with httpPostedFileBase files?

在我的 MVC 项目中,我有一个带有两个上传字段的订单。

我正在尝试将上传的文档附加到电子邮件,但无法正常工作。

我的发送电子邮件功能需要附件列表和附件名称列表如下:

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.InputStreamfile1 的类型为 httpPostedFileBase)但出现转换错误:

Cannot implicitly convert type 'System.IO.Stream' to 'string'

知道怎么做吗?

将上传的文件保存到磁盘,然后将文件位置传递给电子邮件

//...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

确认邮件已发送后,我还会检查确保上传的文件是deleted/removed,否则有可能运行 out disk space .

更新:基于评论

Given that the email portion is custom code that you all use I would first check to see if that is already deleting the files after sending the emails. If not then in the part where you say //rest of code that actually send the email, after sending the email you can simply traverse the attachments list and delete the file based on paths.

//rest of code that actually send the email
foreach(var path in attachments) {
    if(File.Exists(path)) File.Delete(path);
}