将文件作为电子邮件附件

时间:2017-07-25 09:29:58

标签: c# asp.net webforms smtp w3wp

我有一个Web应用程序,可以创建Outlook会议.ics文件并将其作为附件发送给用户。它工作正常,但发送后我无法从服务器删除该文件,因为它正被w3wp.exe使用。 这是我的功能:

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

1 个答案:

答案 0 :(得分:3)

你最后错过了mailMessage.Dispose();