You can save your email data like below:
/// <summary>
/// SentBulkEmail to recipient
/// </summary>
/// <param name="emailModel"></param>
/// <param name="sentBy"></param>
public async Task<CustomResponseModel> SentBulkEmail(SendEmailModel emailModel, int sentBy = 0)
{
CustomResponseModel response = new CustomResponseModel();
try
{
List<EmailSentHistoryModel> lstEmailSentHistory = new List<EmailSentHistoryModel>();
Parallel.ForEach(emailModel.Recipient, (item) =>
{
EmailSentHistoryModel historyModel = new EmailSentHistoryModel();
historyModel.EmailTemplateId = emailModel.EmailTemplateId;
historyModel.IsSent = Utilities.SendEmail(item, emailModel.Description, emailModel.Subject);
historyModel.Recipient = item;
historyModel.Sentdate = DateTime.UtcNow;
historyModel.Sentby = sentBy;
lstEmailSentHistory.Add(historyModel);
});
response = await _emailTemplateRepository.SaveEmailSentHistory(lstEmailSentHistory);
response.Message = "Email sent successfully!!";
}
catch (Exception ex)
{
response.IsSuccess = false;
response.Message = Constant.ServerError;
_logger.LogError("{0}: SentBulkEmail() : {1}", Constant.ServiceError, ex.Message);
}
return response;
}
Below is Email sent method:
public static bool SendEmail(string emailAddress, string body, string subject)
{
var _logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
using (MailMessage mail = new MailMessage(ConfigItems.From, emailAddress))
{
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient()
{
Host = ConfigItems.Host,
EnableSsl = true
};
NetworkCredential NetworkCred = new NetworkCredential(ConfigItems.From, ConfigItems.Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
smtp.EnableSsl = true;
smtp.Port = ConfigItems.Port;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
}
return true;
}
catch (Exception ex)
{
_logger.Error(ex.Message.ToString());
return false;
}
}
You can see in SentBulkEmail I used that method to get whether email and sent or not and also save the data from their as well.