Search code examples
c#wpfsmtpclient

How to know, that email was sent, and attachments can be deleted?


I have a method, which saves screenshot by the definite path and then makes email message, attaching screenshot to it. As I've understood, after sending it - the special thread is being created in which attachment file is used, so I can't delete it while that thread is working. So, I need to know if when the file will be accessible for deleting.

Here's my code:

-- Configuring smtp

private SmtpClient CreateSMTP()
{
    var smtp = new SmtpClient("gate");
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential("notifications@****.com", "3eCMCQxFde");
    smtp.Port = 25;
    smtp.EnableSsl = false;

    return smtp;
}

-- Making message

public MailMessage MakeMessage(bool screenshotFlag)
    {
        MailAddress from = new MailAddress("notifications@****.com", Name);
        MailAddress to = new MailAddress("****@****.com");
        MailMessage message = new MailMessage(from, to);

        message.Subject = Subject == string.Empty ? string.Empty : Subject;
        message.Body = MessageText;
        message.Body = GenerateLogAndExceptionInfo(message.Body);
        message.BodyEncoding = Encoding.Unicode;

        message.ReplyTo = new MailAddress(Mail);

        if (screenshotFlag)
        {
            CreateScreenshot();
            message.Attachments.Add(new Attachment(MailHelper.FeedBackScreenShotPath));
        }

        return message;
    }

-- Sending email

public void SendMessage()
{
    using (SmtpClient smtp = CreateSMTP())
    {
        smtp.Send(MakeMessage(SendWithScreenshot));
    }
}

Solution

  • From the documentation:

    These methods block while the message is being transmitted.

    So while the message is being transmitted, the method blocks. So after the method is done and you've disposed the message instance, you could delete the file.

    Of course, it could still have a lock on the file. That is why I would say you should first dispose the SmtpClient and then try to delete the file (so do that after the using block). It should be fine then.