I am trying to create a program which allows users to create an E-Mail draft for several recipients. The users are allowed to load a .csv file containing the mail-addresses and to choose an attachment. So far everything works, but the E-Mail is only created for the last element in the array.
I've tried a foreach loop and a basic for loop, but none of it is working.
First I created the objects:
var olApplication = new MS.Outlook.Application();
var olMailItem = (MS.Outlook.MailItem)olApplication.CreateItem(MS.Outlook.OlItemType.olMailItem);
var olNamespace = olApplication.GetNamespace("MAPI");
var olUser = olNamespace.CreateRecipient(UserPrincipal.Current.EmailAddress);
var olDrafts = olNamespace.GetSharedDefaultFolder(olUser, MS.Outlook.OlDefaultFolders.olFolderDrafts);
Then I used the mailItem inside the loop(s):
for (int i = 0; i < recipientArray.Length; i++)
{
olMailItem.To = recipientArray[i];
olMailItem.Subject = tbTitle.Text;
olMailItem.Body = tbBody.Text;
if (String.IsNullOrEmpty(attachment))
{
olMailItem.Display(false);
olMailItem.Move(olDrafts);
break;
}
else
olMailItem.Attachments.Add(attachment);
olMailItem.Display(false);
olMailItem.Move(olDrafts);
}
or
foreach (var recipient in recipientArray)
{
olMailItem.To = recipient;
...
}
Both do the same thing. I thought about creating a new milItem everytime in the loop, but I don't know how.
Sorry, I haven't been programming since school (6 years ago, very basic programs) and I really tried searching the web, but that's as far as I could go.
I tried using a foreach loop (for each recipient in recipientArray) but that doesn't work, it only takes the last element in the Array. I've also tried using a for loop (comparing i with the length of the recipientArray) but it also only takes the last element.
When filling a textbox with the filled array, it shows all the content.
foreach (string line in File.ReadAllLines(FileDiagAttachment.FileName))
{
recipientArray = line.Split('\n');
foreach (string recipient in recipientArray)
{
tbTest.Text += recipient.ToString() + "\n";
}
}
I'd gladly appreciate the help.
You need to add a recipient in the loop like the following code shows:
The MailItem.Recipients property returns a
Recipientscollection that represents all the recipients for the Outlook item. Use theAddmethod to create a new Recipient object and add it to the Recipients object. The Type property of a new Recipient object is set to the default for the associatedAppointmentItem,JournalItem,MailItem, orTaskItemobject and must be reset to indicate another recipient type. For example:You may find the following articles that I wrote for the technical blog helpful: