/// <summary> /// Sends an email using the `MailKit` library. /// This method converts a razor template file to an string and then uses it as the email's message. /// </summary> public async Task SendEmailAsync <T>( SmtpConfig smtpConfig, IEnumerable <MailAddress> emails, string subject, string viewNameOrPath, T viewModel, DelayDelivery delayDelivery = null, IEnumerable <string> attachmentFiles = null, MailHeaders headers = null) { var message = await _viewRendererService.RenderViewToStringAsync(viewNameOrPath, viewModel); await SendEmailAsync(smtpConfig, emails, subject, message, delayDelivery, attachmentFiles, headers); }
/// <summary> /// Sends an email using the `MailKit` library. /// </summary> public async Task SendEmailAsync( SmtpConfig smtpConfig, IEnumerable <MailAddress> emails, string subject, string message, IEnumerable <MailAddress> blindCarpbonCopies = null, IEnumerable <MailAddress> carpbonCopies = null, IEnumerable <MailAddress> replyTos = null, 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, blindCarpbonCopies, carpbonCopies, replyTos); 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, blindCarpbonCopies, carpbonCopies, replyTos); await client.SendAsync(emailMessage); count++; if (delayDelivery != null) { if (count % delayDelivery.NumberOfMessages == 0) { await Task.Delay(delayDelivery.Delay); } } } await client.DisconnectAsync(true); } } }