0

In my current WPF project I built in a button, which sends emails to all elements in an array (these elements are persons, which all have an email address referring to). I use System.Net.Mail for this.

Now, the problem is that it takes the button very long to send all these emails, even with one email sent it takes about a second to send. So the program is for this certain time not usable, you have to wait until all emails have been sent. This interrupts everything of course and is not wished.

Is there a way to accelerate this process?

This is my used code for sending the email:

string[] myArray = myList.ToArray();

foreach (string str in myArray)
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

    mail.From = new MailAddress("myMail@Adress.com", "myEmailName");
    mail.To.Add(targetEmailAdress);
    mail.Subject ="mySubject";

    mail.IsBodyHtml = true;
    string htmlBody;

    htmlBody =
        "<html> " +
        "<body>" +
        "<p>MyText123</p>" +
        "</body> " +
        "</html>";

    mail.Body = htmlBody;

    SmtpServer.Port = myPort;
    SmtpServer.Credentials = new System.Net.NetworkCredential("myMail@Adress.com", @"myPassword");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);
}
funie200
  • 3,688
  • 5
  • 21
  • 34
  • 2
    maybe this will help you? [link](https://stackoverflow.com/questions/7276375/what-are-best-practices-for-using-smtpclient-sendasync-and-dispose-under-net-4) Use Async method to not block you program – Amir Feldman Jan 14 '21 at 09:21
  • I'd say google doesn't want you to spam large lists of email addresses. You could likely do this in parallel, however see first point ,google is not really going to want you spamming. If you have large mailing lists, use a service which is more inline with your desires – TheGeneral Jan 14 '21 at 09:28
  • If you're sending many emails, an email delivery service such as SendGrid (others exist as well) might be more appropriate – canton7 Jan 14 '21 at 09:29
  • Use [`SmtpClient.SendAsync`](https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.sendasync?view=net-5.0). This won't make a single email go out faster but will improve application performance and throughput. – Aluan Haddad Jan 14 '21 at 11:18

0 Answers0