This is my function. I already wrapped both client and message into using clause and still get error when run code inspection. Error points to first 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);
}
}
}
This is warning I get:
Warning 1 CA2000 :
Microsoft.Reliability : In method
‘Email.Send(MailItem)’, object
‘<>g_initLocal0′ is not disposed
along all exception paths. Call
System.IDisposable.Dispose on object
‘<>g_initLocal0′ before all
references to it are out of
scope. C:\CodeWorkspace\Code\Utility\Email.cs 41
Your problem is this line:
The initializer block
{ From = ... }is executed after the object is constructed and before theusingblock’s internaltry/finallybegins.If the
MailAddressconstructor (or its argument expressions, or the assignment toFromif it is a property accessor) throws an exception, theMailMessagewill not be disposed.Change to:
The temporary
<>g_initLocal0variable is the name of the MailMessage before it gets assigned tomsg.