public bool Handle(TransportMessage transportMessage) { var sendEmail = MessageSerializer.DeserializeMessage(transportMessage); using (var smtpClient = SmtpBuilder.BuildClient()) using (var mailMessage = sendEmail.ToMailMessage()) { AddAttachments(sendEmail, mailMessage); try { smtpClient.Send(mailMessage); CleanAttachments(sendEmail); } catch (SmtpFailedRecipientsException ex) { //TODO: should put some delay in here to back off from an overloaded smtp server var originalRecipientCount = mailMessage.To.Count + mailMessage.Bcc.Count + mailMessage.CC.Count; if (ex.InnerExceptions.Length == originalRecipientCount) { //All messages failed. So safe to throw and cause a re-handle of the message throw; } var timeSent = TimeSent(transportMessage); foreach (var newMessage in RetryMessageBuilder.GetMessagesToRetry(sendEmail, timeSent, ex)) { Bus.Send(InputAddress, newMessage); } } } return(true); }
public async Task OnMessageReceived(IBuilder builder, MessageContext messageContext) { if (dispatchMessages == null) { dispatchMessages = builder.Build <IDispatchMessages>(); } var sendEmail = serializer.DeserializeMessage(messageContext); using (var smtpClient = buildSmtpClient()) using (var mailMessage = sendEmail.ToMailMessage()) { await AddAttachments(sendEmail, mailMessage); try { await smtpClient.SendMailAsync(mailMessage) .ConfigureAwait(false); await CleanAttachments(sendEmail) .ConfigureAwait(false); } catch (SmtpFailedRecipientsException exception) { //TODO: should put some delay in here to back off from an overloaded smtp server var originalRecipientCount = mailMessage.To.Count + mailMessage.Bcc.Count + mailMessage.CC.Count; if (exception.InnerExceptions.Length == originalRecipientCount) { //All messages failed. So safe to throw and cause a re-handle of the message throw; } var timeSent = TimeSent(messageContext); var retries = RetryMessageBuilder.GetMessagesToRetry(sendEmail, timeSent, exception) .Select(newMessage => DispatchMailMessage(messageContext, newMessage)); await Task.WhenAll(retries); } } }