You could use a HashSet to remember the dialogs already processed. Store a concatenation of recipient, separator character (eg '~') and attachment as HashSet
item. Use the Contains()
method to find if the current combination has been there already.
By the way:
In your code you could use the following statement:
using Outlook = Microsoft.Office.Interop.Outlook;
This allows you to use Outlook
rather than the lengthy Microsoft.Office.Interop.Outlook
to shorten your code and clean it up.
The code could look like this:
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Collections.Generic;
namespace nsXYZ
{
class AClass
{
private void emailReports()
{
HashSet<String> diaSet = new HashSet<String>();
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
String s;
foreach (DataGridViewRow recRow in dgvTests.Rows)
{
if (((recRow.Cells["Select"].Value != null) && Boolean.Parse(recRow.Cells["Select"].Value.ToString())))
{
mail = null;
// If Business should be contacted with Sample Test Results
if ((recRow.Cells["BusinessContactResults"].Value != null) && (Boolean.Parse(recRow.Cells["BusinessContactResults"].Value.ToString()) == true) && (recRow.Cells["BusinessEmail"].Value != null))
{
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
mail.To = recRow.Cells["BusinessEmail"].Value.ToString();
mail.Attachments.Add((object)string.Format("{0}IN_{1}_{2}_{3}_BUS.pdf", reptLoc, strLSN, recRow.Cells["BusinessID"].Value, dtString), Outlook.OlAttachmentType.olEmbeddeditem, 1, (object)"Attachment");
}
if ((recRow.Cells["SupplierContactResults"].Value != null) && (Boolean.Parse(recRow.Cells["SupplierContactResults"].Value.ToString()) == true) && (recRow.Cells["SupplierEmail"].Value != null))
{
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
mail.To = recRow.Cells["SupplierEmail"].Value.ToString();
mail.Attachments.Add((object)string.Format("{0}IN_{1}_{2}_{3}_SUP.pdf", reptLoc, strLSN, recRow.Cells["BusinessID"].Value, dtString), Outlook.OlAttachmentType.olEmbeddeditem, 1, (object)"Attachment");
}
if ((recRow.Cells["CorporateContactResults"].Value != null) && (Boolean.Parse(recRow.Cells["CorporateContactResults"].Value.ToString()) == true) && (recRow.Cells["CorporateEmail"].Value != null))
{
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
mail.To = recRow.Cells["CorporateEmail"].Value.ToString();
mail.Attachments.Add((object)string.Format("{0}IN_{1}_{2}_{3}_CRP.pdf", reptLoc, strLSN, recRow.Cells["BusinessID"].Value, dtString), Outlook.OlAttachmentType.olEmbeddeditem, 1, (object)"Attachment");
}
if ((mail != null) && !diaSet.Contains(s = mail.To + "~" + mail.Attachments[0]))
{
diaSet.Add(s);
mail.Subject = "Inspection Notification";
mail.Body = "";
mail.Display();
}
}
}
}
}