Reputation: 578
I want to add all emails in my datatable to the To: of my email - I have tried the below code, but it adds a semi-colon after each char in the email address. How do I need to re-write this so that each email address is added?
foreach (DataRow dr in datatatblefirst.Rows)
{
foreach (char eadd in r["Email"].ToString())
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Body";
oMsg.Subject = "Your Subject will go here.";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
foreach (char email in r["Email"].ToString())
oRecips.Add(eadd.ToString());
oMsg.Save();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
}
Upvotes: 1
Views: 336
Reputation: 16711
It looks like you are iterating over each char
in an email address.
If r["Email"]
contains one email address you can just loop over the data rows. The code below will create one email message per email address:
foreach (DataRow dr in datatatblefirst.Rows)
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Body";
oMsg.Subject = "Your Subject will go here.";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
string emailAddress = r["Email"].ToString();
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(emailAddress);
oRecip.Resolve();
oMsg.Save();
//oMsg.Send();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
To create only one email and send to multiple addresses, create the email before the foreach
:
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Body";
oMsg.Subject = "Your Subject will go here.";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
foreach (DataRow dr in datatatblefirst.Rows)
{
string emailAddress = r["Email"].ToString();
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(emailAddress);
oRecip.Resolve();
}
oMsg.Save();
//oMsg.Send();
oRecips = null;
oMsg = null;
oApp = null;
The line oRecip.Resolve();
is not required. If the contact exists in the address book it will format the email address as Some Name <[email protected]>
.
The addresses can be added simply using oRecips.Add(emailAddress);
without creating or resolving the Recipient
object.
Upvotes: 1