Search code examples
c#asp.netwebformssmtpw3wp

File get stuck in w3wp.exe after sending it as email attachment


I have a web application that creates an Outlook meeting .ics file and sends it as an attachment to the user. It works fine, but after sending it I can't delete the file from the server, due it's being used by w3wp.exe. Here's my function:

public static void SendEmail(string subject, string body, List<string> to, string path)
{
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("no-reply@company.com", "Test email");
    foreach (string item in to)
    {
        mailMessage.To.Add(item);
    }
    mailMessage.Subject = subject;
    mailMessage.BodyEncoding = Encoding.UTF8;
    mailMessage.Body += body;
    mailMessage.IsBodyHtml = true;
    SmtpClient smtpClient = new SmtpClient("smtp.company.com");
    if (!string.IsNullOrEmpty(path))
    {
        Attachment attachment = new Attachment(path);
        mailMessage.Attachments.Add(attachment);
    }
    smtpClient.Send(mailMessage);
}

Solution

  • You miss the mailMessage.Dispose(); at the end.