当使用c#自带的MailMessage类发送excel附件时,再次打开excel会提示处于锁定状态。
解决思路:Attachment是添加附件的类,邮件发送后没有释放该类
public string SendSmtpeMail(string strSmtpServer, string strFrom, string strFromPass, string strto, string strSubject, string strBody, string excelPath)
{
try
{
//这样写防止发送excel附件后,excel处于锁定状态
using (var message = new MailMessage(strFrom, strto, strSubject, strBody))
{
using (var attachment = new Attachment(excelPath)) //添加附件
{
message.Attachments.Add(attachment);
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
using (var client = new SmtpClient(strSmtpServer))
{
client.Timeout = 9999999;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(strFrom, strFromPass);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(message);
}
}
}
}
catch (Exception ex)
{
Program.form.text.Invoke(ex.ToString());
return ex.ToString();
}
return "";
}