Исключение при удалении файла, прикрепленного к отправленной электронной почте - PullRequest
0 голосов
/ 12 октября 2018

После успешной отправки письма с вложением необходимо удалить файлы, которые я отправил как вложение.Файлы используются, поэтому у меня есть исключение.

Я использовал код документации.Я использую метод для создания и отправки электронного письма, чтобы все автоматически удалялось после его вызова.

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 голосов
/ 12 октября 2018

Вам необходимо избавиться от потока, который вы открыли для вложения:

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