private async Task <bool> SendMail(EmailWorkerModel requestLog) { string fileName = ""; Attachment attachment = null; if (!string.IsNullOrEmpty(requestLog.Location)) { fileName = Path.Combine(AppConstants.FileDirectory, requestLog.Location); if (File.Exists(fileName)) { attachment = new Attachment(fileName, MediaTypeNames.Application.Octet) { Name = requestLog.Name + ".csv" }; } } MailMessage message = new MailMessage( _AdminContact, requestLog.emailAddress, "Your Comment Request is Ready", "Find attached your comments as requested"); // Add the file attachment to this e-mail message. if (attachment != null) { message.Attachments.Add(attachment); } else { message.Body = "Sorry, the website you submitted is not yet supported or Comment/Review is disabled."; } try { await _smtpClient.SendMailAsync(message); } catch (Exception ex) { _logger.LogError(ex, $"Failed to send Email, {ex.Message}"); } return(true); }
private async Task FetchAndSendEmail(CommentsDbContext dbContext) { using (var command = dbContext.Database.GetDbConnection().CreateCommand()) { command.CommandText = "Select c.Location, c.Name,c.Disabled, cq.emailAddress, cq.Id from Comments" + " as c inner join CommentRequests as cq on c.id = cq.CommentId " + "where (c.Fetched = 1 or c.Disabled = 1) and cq.emailed = 0"; await command.Connection.OpenAsync(); DbDataReader reader = await command.ExecuteReaderAsync(); if (reader.HasRows) { while (await reader.ReadAsync()) { // do something with each in the list or just return the list var id = reader["Id"].ToString(); _logger.LogInformation($"sending mail for {reader["Name"].ToString() }, {reader["Location"].ToString()}"); var commentRequest = await dbContext.CommentRequests.FindAsync(Convert.ToInt32(id)); var request = new EmailWorkerModel { emailAddress = reader["emailAddress"].ToString(), Id = Convert.ToInt32(reader["Id"].ToString()), Location = reader["Location"].ToString(), Name = reader["Name"].ToString(), }; commentRequest.emailed = await SendMail(request); commentRequest.dateSent = DateTime.UtcNow; dbContext.Attach(commentRequest); dbContext.Entry(commentRequest).State = EntityState.Modified; await dbContext.SaveChangesAsync(); } command.Connection.Close(); } return; } }