将带有附件的电子邮件附加到另一封电子邮件中

时间:2011-04-25 14:05:46

标签: asp.net c#-4.0 system.net.mail

所以我知道如何发送带附件的电子邮件......这很简单。

现在的问题是我需要将一个MailMessage添加到另一个MailMessage中,该MailMessage具有自己的附件。这将允许用户查看内容并获取预先制作的电子邮件,并在一切正常时发送。

我不确定这将是最后的工作流程,但我想知道是否容易。

我看到一堆软件用于赚钱,收到这些电子邮件的用户将使用Outlook客户端。

这将部署到廉价的共享托管解决方案,必须能够在Meduim Trust中运行!

我宁愿不必使用第三方软件,No $ :(

任何想法都会很棒。

2 个答案:

答案 0 :(得分:1)

MailMessages无法附加到其他MailMessages。你要做的是创建一个.msg文件,它基本上是一个存储电子邮件及其所有附件的文件,并将其附加到你的实际MailMessage。 Outlook支持MSG文件。

有关文件扩展名的更多信息,请访问:http://www.fileformat.info/format/outlookmsg/

答案 1 :(得分:0)

正如贾斯汀所说,没有办法在API中将一个MailMessage附加到另一个。我使用SmtpClient来解决这个问题,将我的内部消息“传递”到一个目录,然后将生成的文件附加到我的外部消息中。这个解决方案不是非常吸引人,因为它必须使用文件系统,但它确实完成了工作。如果SmtpDeliveryMethod有一个Stream选项会更清晰。

有一点需要注意,SmtpClient在创建消息文件时为SMTP信封信息添加了X-Sender / X-Receiver标头。如果这是一个问题,您必须在附加之前将它们从消息文件的顶部剥离。

// message to be attached
MailMessage attachedMessage = new MailMessage("bob@example.com"
    , "carol@example.com", "Attached Message Subject"
    , "Attached Message Body");

// message to send
MailMessage sendingMessage = new MailMessage();
sendingMessage.From = new MailAddress("ted@example.com", "Ted");
sendingMessage.To.Add(new MailAddress("alice@example.com", "Alice"));
sendingMessage.Subject = "Attached Message: " + attachedMessage.Subject;
sendingMessage.Body = "This message has a message attached.";

// find a temporary directory path that doesn't exist
string tempDirPath = null;
do {
    tempDirPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
} while(Directory.Exists(tempDirPath));
// create temp dir
DirectoryInfo tempDir = Directory.CreateDirectory(tempDirPath);

// use an SmptClient to deliver the message to the temp dir
using(SmtpClient attachmentClient = new SmtpClient("localhost")) {
    attachmentClient.DeliveryMethod
        = SmtpDeliveryMethod.SpecifiedPickupDirectory;
    attachmentClient.PickupDirectoryLocation = tempDirPath;
    attachmentClient.Send(attachedMessage);
}

tempDir.Refresh();
// load the created file into a stream
FileInfo mailFile = tempDir.GetFiles().Single();
using(FileStream mailStream = mailFile.OpenRead()) {
    // create/add an attachment from the stream
    sendingMessage.Attachments.Add(new Attachment(mailStream
        , Regex.Replace(attachedMessage.Subject
            , "[^a-zA-Z0-9 _.-]+", "") + ".eml"
        , "message/rfc822"));

    // send the message
    using(SmtpClient smtp = new SmtpClient("smtp.example.com")) {
        smtp.Send(sendingMessage);
    }
    mailStream.Close();
}

// clean up temp
mailFile.Delete();
tempDir.Delete();
相关问题