I am using asp.net v4 c# and I have a list of email addresses. I want one of my admins to be able to type a message, press "SEND" and for the emails to go out one by one.
The best way I think is to make use of the async methods in .net? OnClick of the send button, I take the list of email addresses then call the async method. I just don't know how to get it to loop through the list one by one and fire off the email.
Is needs to be done one at a time so that I can save a copy of the email sent against that user's account.
Here's what I have so far (cobbled together from tutorials / posts on here)
protected void btnSend_Click(object sender, EventArgs e)
{
//get a list of email addresses and send to them
//these will come from the database once testing comp
List<string> emails = new List<string>();
emails.Add("test1@test.com");
emails.Add("test2@test.com");
emails.Add("test3@test.com");
emails.Add("test4@test.com");
emails.Add("test5@test.com");
emails.Add("test6@test.com");
emails.Add("test7@test.com");
SendingDelegate worker = new SendingDelegate(DoSend);
AsyncCallback completedCallback = new AsyncCallback(DoSendCompletedCallBack);
lblThreadDetails.Text = "sending to " + emails.Count.ToString() + " email addresses";
worker.BeginInvoke(completedCallback, AsyncOperationManager.CreateOperation(null));
sending = true;
}
//boolean flag which indicates whether the async task is running
private bool sending = false;
private delegate bool SendingDelegate();
private bool DoSend()
{
//send messages
//emails sent here and saved in the DB each time
//give the user some feed back on screen. X should be the email address.
lblThreadDetails.Text = "processing " + x.ToString();
Thread.Sleep(1000);
return false;
}
private void DoSendCompletedCallBack(IAsyncResult ar)
{
//get the original worker delegate and the AsyncOperation instance
SendingDelegate worker = (SendingDelegate)((AsyncResult)ar).AsyncDelegate;
//finish the asynchronous operation
bool success = worker.EndInvoke(ar);
sending = false;
if (success)
{
//perform sql tasks now that crawl has completed
lblThreadDetails.Text = "all done!";
}
}
I basically need to put the calling of the async function in to a loop where I go through the list of email addresses.
Does this approach make sense?