在 MVC 中将 Outlook 邮件项目返回给客户端

Returning Outlook Mail Item to Client in MVC

在高层次上,我正在尝试在服务器端生成一个 Outlook 电子邮件项目,然后 return 将其发送到客户端,以便它在他们的本地 Outlook 中打开,允许他们进行任何他们想要的更改(这与通过 SMTP 发送电子邮件相对)。

这真的是我第一次使用文件流,我不确定如何继续。我有一个非常基本的开始,我正在尝试做,最初只是让 Outlook 在这个控制器操作 returns 邮件项目之后打开。此代码是在控制器中调用以创建邮件项的代码。我没有任何添加各种电子邮件地址、正文、主题等的逻辑,因为它们并不真正相关。此代码也由控制器操作调用,只是将它放在这里以防我在创建邮件项目时也做错了。

     public MailItem CreateEmail(int id)
    {
        Application app = new Application();
        MailItem email = (MailItem)app.CreateItem(OlItemType.olMailItem);
        email.Recipients.Add("example@example.com");
        return email;
    }

这是我想 return 这个 MailItem 到客户端的控制器操作。 (这是通过 AJAX 调用的)

    public ActionResult GenerateEmail(int id)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            BinaryFormatter format = new BinaryFormatter();
            format.Serialize(ms, logic.CreateEmail(id));
            return File(ms, "message/rfc822");
        }
    }

代码在 format.Serialize 中断,提示我的 _COM 对象无法序列化。有没有办法做我想做的事情,或者我应该寻找其他方法来实现这个目标?

首先,Outlook Object模型不能在服务(如IIS)中使用。其次,既然你只是指定收件人地址,为什么不在客户端使用mailto link?

如果您仍想发送邮件,可以生成一个 EML (MIME) 文件 - Outlook 应该可以正常打开它。要使其看起来未发送,请使用 X-Unsent MIME header。

主要基于 here

中的代码
public ActionResult DownloadEmail()
{
    var message = new MailMessage();

    message.From = new MailAddress("from@example.com");
    message.To.Add("someone@example.com");
    message.Subject = "This is the subject";
    message.Body = "This is the body";

    using (var client = new SmtpClient())
    {
        var id = Guid.NewGuid();

        var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);

        tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp");

        // create a temp folder to hold just this .eml file so that we can find it easily.
        tempFolder = Path.Combine(tempFolder, id.ToString());

        if (!Directory.Exists(tempFolder))
        {
            Directory.CreateDirectory(tempFolder);
        }

        client.UseDefaultCredentials = true;
        client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
        client.PickupDirectoryLocation = tempFolder;
        client.Send(message);

        // tempFolder should contain 1 eml file

        var filePath = Directory.GetFiles(tempFolder).Single();

        // stream out the contents - don't need to dispose because File() does it for you
        var fs = new FileStream(filePath, FileMode.Open);
        return File(fs, "application/vnd.ms-outlook", "email.eml");
    }
}

这在 Chrome 中工作正常,但 IE 不想打开它,也许它有一些额外的安全功能。尝试摆弄内容类型和文件扩展名,您也许可以同时使用它们。