这是我的功能。我已将客户端和消息都包装到using子句中,并在运行代码检查时仍然出错。错误指向首先使用line:
public static void Send(MailItem mail)
{
var sender = Membership.GetUser(mail.CreatedBy);
if (sender == null)
{
return;
}
using (var msg = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]) })
{
foreach (var recipient in mail.MailRecipients)
{
var recipientX = Membership.GetUser(recipient.UserKey);
if (recipientX == null)
{
continue;
}
msg.To.Add(new MailAddress(recipientX.Email, recipientX.UserName));
}
msg.Subject = "[From: " + sender.UserName + "]" + mail.Subject;
msg.Body = mail.Body;
if (HttpContext.Current != null)
{
msg.Body += Environment.NewLine + Environment.NewLine + "To reply via Web click link below:" +
Environment.NewLine;
msg.Body += ConfigurationManager.AppSettings["MailPagePath"] + "?AID=" +
ContextManager.CurrentAccount.AccountId + "&RUN=" + sender.UserName;
}
try
{
using (var emailClient = new SmtpClient())
{
emailClient.Send(msg);
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
}
这是我得到的警告:
警告1 CA2000: Microsoft.Reliability:方法 'Email.Send(MailItem)',对象 '<> g_ initLocal0'未被处置 沿着所有异常路径。呼叫 System.IDisposable.Dispose on object 毕竟'<> g _initLocal0' 对它的引用是出于 范围。 C:\ CodeWorkspace \ Code \ Utility \ Email.cs 41
答案 0 :(得分:18)
你的问题就在这一行:
using (var msg = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]) })
初始化程序块{ From = ... }
在构造对象之后和using
块的内部try/finally
开始之前执行。
如果MailAddress
构造函数(或其参数表达式,或From
的赋值(如果它是属性访问器))抛出异常,则MailMessage
将不会被处理。
更改为:
using (var msg = new MailMessage())
{
msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"], ConfigurationManager.AppSettings["EmailSenderName"]);
...
}
临时<>g_initLocal0
变量是MailMessage在被分配到msg
之前的名称。