Consider this code
private MailMessage GetMailMessageFromMailItem(Data.SystemX.MailItem mailItem)
{
var msg = new MailMessage();
foreach (var recipient in mailItem.MailRecipients)
{
var recipientX = Membership.GetUser(recipient.UserKey);
if (recipientX == null)
{
continue;
}
msg.To.Add(new MailAddress(recipientX.Email, recipientX.UserName));
}
msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"],
ConfigurationManager.AppSettings["EmailSenderName"]);
msg.Subject = sender.UserName;
if (!string.IsNullOrEmpty(alias)) msg.Subject += "(" + alias + ")";
msg.Subject += " " + mailItem.Subject;
msg.Body = mailItem.Body;
msg.Body += Environment.NewLine + Environment.NewLine + "To reply via Web click link below:" + Environment.NewLine;
msg.Body += ConfigurationManager.AppSettings["MailPagePath"] + "?AID=" + ContextManager.AccountId + "&RUN=" + sender.UserName;
if (mailItem.MailAttachments != null)
{
foreach (var attachment in mailItem.MailAttachments)
{
msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data), attachment.Name));
}
}
return msg;
}
I'm just taking my database type and converting to MailMessage. It get's sent in another function.
Code analysis tells me I'm not disposing "msg" which is correct. But if I do it here - I get exception when I'm trying to send it.
Also, it complains about not disposing MemoryStream here:
msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data), attachment.Name));
I have no idea on how to properly dispose it. I tried different things but was getting exceptions when sending mail saying "Stream is closes"