using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
public class EmailSender
{
readonly string _clientAddress;
public EmailSender(string client)
{
_clientAddress = client;
}
public void SendEmails(List<MailMessage> message)
{
var totalMessages = message.Count;
var tasks
= new List
<Task
>(); foreach (var item in message)
{
tasks.Add(SendMailAsync(item));
}
while (tasks.Count > 0)
{
var idx = Task.WaitAny(tasks.ToArray());
tasks.RemoveAt(idx);
}
}
async Task SendMailAsync(MailMessage message)
{
await Task.Run(() =>
{
SendEmail(message);
});
}
public void SendEmail(MailMessage message, int tryCount = 0)
{
try
{
using (var client
= new SmtpClient
(_clientAddress
)) {
client.Send(message);
}
}
catch(Exception)
{
if (tryCount > 3)
throw;
SendEmail(message, tryCount++);
}
}
}