Hi, I have an asp.net core app that needs to send many emails at the same time where each email having a different message.
I installed Mimekit and i supply my email settings accordingly. In my app the user creates a project, then inputs all the email adresses he wants to notify about the project. This list is a string that I put into a list of strings based on the commas separating the emailinput. then i remove whitespace (not sure how efficient this is, i got it from stackoverflow):
string emailList; List<string> list = emailList.Split(',').ToList(); //removes whitespace in list: for (int i = 0; i < list.Count(); i++) { list[i] = string.Join("", list[i].Split(default(string[]), StringSplitOptions.RemoveEmptyEntries)); }
It works. I can now use mimekit to send emails to these adresses in the list.
TLDR: the only way i can see on how to send many unique emails would be to loop over this list and then use the normal SendEmail method in mimekit:
I need to send a unique numer in a link with each email, so when the click it I can provide them with their individual online test:
string link = "http://www.mywebsite.com/Test/"; string message = "Press this link to take the test"; int number = 0; foreach(var email in emailList) { //gets a unique number stored in a table for each person: number = GetNumber(email); message = link + number; await _emailSender.SendEmailAsync(email, "Subject", message); }
Now the emailSender uses the normal mimekit method to send one email for each in the list.
This takes a long time for a big list. Are there any other ways to do it, or can I write this more effectively? What could be the bottlenecks of my solution? Any feedback would be great, from my bad async code to security.
Here is just the mimekit code to send the email:
public async Task SendEmailAsync(string email, string subject, string message) { var melding = new MimeMessage(); melding.From.Add(new MailboxAddress("Frank", _options.Option1)); melding.To.Add(new MailboxAddress(email)); melding.Subject = subject; melding.Body = new TextPart("plain") { Text = message }; Try { await SendMessage(melding); } catch(Exception ex) { //log error throw new ApplicationException($"something went wrong:'{ex.Message}'."); } } private async Task SendMessage(MimeMessage message) { using (var client = new SmtpClient()) { await client.ConnectAsync("smtp.WebSiteLive.net", 587, SecureSocketOptions.None); client.AuthenticationMechanisms.Remove("XOAUTH2"); // Must be removed for Gmail SMTP await client.AuthenticateAsync(_options.Option1, _options.Option2); await client.SendAsync(message); await client.DisconnectAsync(true); } }
any help greately apprechiated!!