static void TrySendEmailBySendGrid(UserMessageTransaction tran) { Task.Run(() => { var dtNow = "\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": "; try { var toEmails = new List <SendGridRequest.Email>() { new SendGridRequest.Email() { email = tran.To, name = tran.ToName } }; var fromEmail = new SendGridRequest.Email() { email = tran.From }; var res = SendGridHelper.SendEmail(toEmails, tran.Subject, tran.Content, fromEmail); if (res.StatusCode == HttpStatusCode.Accepted) { UpdateTranStatus(tran.Id, Enums.UserMessageTransactionStatus.Sent, $"{dtNow}Success"); } else { UpdateTranStatus(tran.Id, Enums.UserMessageTransactionStatus.Fail, dtNow + res.StatusCode + " " + string.Join(" ", res.errors)); } } catch (Exception ex) { UpdateTranStatus(tran.Id, Enums.UserMessageTransactionStatus.Fail, dtNow + ex.GetMessages()); } }); }
public void Handle(SendEmailToUser c) { var defaultFromEmail = SendGridHelper.DefaultFromEmail; var tran = new UserMessageTransaction() { Id = c.MessageTransactionId, Content = c.Content, From = defaultFromEmail, To = c.ToEmail, ToName = c.ToName, Subject = c.Subject, Type = (short)Enums.UserMessageType.Email, Status = (short)Enums.UserMessageTransactionStatus.Created, ToUserId = c.UserId, SendDate = c.SendDate, CreatedDate = c.CreatedDate }; using (var db = new CoreDbContext()) { db.UserMessageTransactions.Add(tran); db.SaveChanges(); } }