发送邮件中删除文件的异常

时间:2018-10-12 10:48:07

标签: c# mimekit

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

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

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);
}

怎么了?有人可以帮助我吗? 谢谢

1 个答案:

答案 0 :(得分:1)

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

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 ();