首页 > 解决方案 > 删除附加到已发送电子邮件的文件时出现异常

问题描述

成功发送带附件的电子邮件后,我必须删除作为附件发送的文件。文件正在使用中,所以我有一个例外。

我已经使用了文档的代码。我正在使用一种方法来创建和发送电子邮件,以便在调用它后自动处理所有内容。

MimeMessage eMail = new MimeMessage();
eMail.From.Add (new MailboxAddress(fromDescription, fromAddress));
foreach (string to in toAddress)
    eMail.To.Add(new MailboxAddress(to));
if (ccAddress != null)
    foreach (string cc in ccAddress)
        eMail.Cc.Add(new MailboxAddress(cc));
if (ccnAddress != null)
    foreach (string ccn in ccnAddress)
        eMail.Bcc.Add(new MailboxAddress(ccn));
eMail.Subject = subject;
var Body = new TextPart("plain")
{
    Text = body
};

// now create the multipart/mixed container to hold the message text and the attachment
var multipart = new Multipart("mixed");
multipart.Add(Body);

if (attachments != null)
{
    foreach (string attachmentPath in attachments)
    {
        // create an attachment for the file located at path
        var attachment = new MimePart(MimeTypes.GetMimeType(attachmentPath))
        {
            Content = new MimeContent(File.OpenRead(attachmentPath), ContentEncoding.Default),
            ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
            ContentTransferEncoding = ContentEncoding.Base64,
            FileName = Path.GetFileName(attachmentPath)
        };
        multipart.Add(attachment);
    }
}

// now set the multipart/mixed as the message body
eMail.Body = multipart;

using (var client = new SmtpClient())
{
    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
    //client.ServerCertificateValidationCallback = (s, c, h, e) => true;

    client.Connect(SmtpHost, SmtpPort, SecureSocketOptions.SslOnConnect);

    // Note: since we don't have an OAuth2 token, disable
    // the XOAUTH2 authentication mechanism.
    //client.AuthenticationMechanisms.Remove("XOAUTH2");

    // Note: only needed if the SMTP server requires authentication
    client.Authenticate(SmtpUser, SmtpPassword);

    client.Send(eMail);
    client.Disconnect(true);
}

怎么了?任何人都可以帮助我吗?谢谢

标签: c#mimekit

解决方案


您需要处理为附件打开的流:

File.OpenRead(attachmentPath)

你可以这样做:

var streams = new List<Stream> ();

if (attachments != null) {
    foreach (string attachmentPath in attachments) {
        // create an attachment for the file located at path
        var stream = File.OpenRead(attachmentPath);
        var attachment = new MimePart(MimeTypes.GetMimeType(attachmentPath)) {
            Content = new MimeContent(stream, ContentEncoding.Default),
            ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
            ContentTransferEncoding = ContentEncoding.Base64,
            FileName = Path.GetFileName(attachmentPath)
        };
        multipart.Add(attachment);
        streams.Add (stream);
    }
}

然后,在发送消息后,执行以下操作:

foreach (var stream in streams)
    stream.Dispose ();

推荐阅读