/// <summary> /// Sends an email using the `MailKit` library. /// </summary> public async Task SendEmailAsync( SmtpConfig smtpConfig, IEnumerable <MailAddress> emails, string subject, string message, DelayDelivery delayDelivery = null, IEnumerable <string> attachmentFiles = null, MailHeaders headers = null) { if (smtpConfig.UsePickupFolder) { const int maxBufferSize = 0x10000; // 64K. foreach (var email in emails) { using (var stream = new FileStream( Path.Combine(smtpConfig.PickupFolder, $"email-{Guid.NewGuid().ToString("N")}.eml"), FileMode.CreateNew, FileAccess.Write, FileShare.None, maxBufferSize, useAsync: true)) { var emailMessage = getEmailMessage(email.ToName, email.ToAddress, subject, message, attachmentFiles, smtpConfig, headers); await emailMessage.WriteToAsync(stream); } } } else { using (var client = new SmtpClient()) { if (!string.IsNullOrWhiteSpace(smtpConfig.LocalDomain)) { client.LocalDomain = smtpConfig.LocalDomain; } await client.ConnectAsync(smtpConfig.Server, smtpConfig.Port, SecureSocketOptions.Auto); if (!string.IsNullOrWhiteSpace(smtpConfig.Username) && !string.IsNullOrWhiteSpace(smtpConfig.Password)) { await client.AuthenticateAsync(smtpConfig.Username, smtpConfig.Password); } var count = 0; foreach (var email in emails) { var emailMessage = getEmailMessage(email.ToName, email.ToAddress, subject, message, attachmentFiles, smtpConfig, headers); await client.SendAsync(emailMessage); count++; if (delayDelivery != null) { if (count % delayDelivery.NumberOfMessages == 0) { await Task.Delay(delayDelivery.Delay); } } } await client.DisconnectAsync(true); } } }