예제 #1
0
        public async Task <MailMessageStatus> Enqueue(TaggedMessage message)
        {
            if (string.IsNullOrWhiteSpace(message.To))
            {
                throw new Exception("invalid-recipient");
            }

            var status = new MailMessageStatus
            {
                ReferenceId = message.ReferenceId,
                MessageId   = message.MessageId,
                Timestamp   = DateTime.UtcNow,
                Status      = MessageStatus.pending.ToString()
            };

            string errorMessage = "";

            if (!_queue.TryAdd(message))
            {
                status.Status = MessageStatus.failure.ToString();
                errorMessage  = "Unable to add message to queue.";
            }

            await _cache.SetStringAsync(
                status.ReferenceId,
                JsonSerializer.Serialize(status),
                _cacheOptions
                );

            _logger.LogDebug(logMsg, message.To, message.ClientName, status.Status, errorMessage);
            return(status);
        }
예제 #2
0
        public void ProcessQueue()
        {
            foreach (var source in _queue.GetConsumingEnumerable())
            {
                var status = new MailMessageStatus
                {
                    ReferenceId = source.ReferenceId,
                    MessageId   = source.MessageId
                };


                if (!source.From.HasValue())
                {
                    source.From = _options.Sender;
                }

                source.Cc += $";{_options.CcRecipients}";

                source.Bcc += $";{_options.BccRecipients}";

                if (source.BccSender)
                {
                    source.Bcc += $";{source.From}";
                }

                var message = source.ToMimeMessage();

                try
                {
                    // client.Send(FormatOptions.Default, message);
                    status.Status = MessageStatus.success.ToString();
                    _logger.LogInformation(logMsg, source.To, source.ClientName, "succeeded", "");
                }
                catch (Exception ex)
                {
                    status.Status = MessageStatus.failure.ToString();
                    _logger.LogError(logMsg, source.To, source.ClientName, "failed", ex.Message);
                }


                status.Timestamp = DateTime.UtcNow;

                _cache.SetString(
                    status.ReferenceId,
                    JsonSerializer.Serialize(status),
                    _cacheOptions
                    );

                if (_queue.Count == 0)
                {
                    // client.Disconnect(true);
                    _logger.LogDebug("Queue empty; disconnected mock smtp client.");
                }
            }
        }
예제 #3
0
        // public static event Func<List<UserAccountModel>, NotificationObjectType, IEmailStatus> OnEmailNotification;

        /// <summary>
        /// Sends notifications by emial to a collection of UserAccount objects, the emails tempaltes will be created based on the object type.
        /// </summary>
        /// <param name="notificationReceivers"></param>
        /// <param name="notificationObjectType"></param>
        /// <param name="actionType"></param>
        /// <returns></returns>
        public static MailMessageStatus Email <T>(List <UserAccountModel> notificationReceivers,
                                                  NotificationObjectType notificationObjectType,
                                                  T additionalData,
                                                  ActionType actionType = ActionType.NotSpecified)
        {
            MailMessageStatus status = null;

            foreach (var user in notificationReceivers)
            {
                var emailComposer = EmailsComposor.ComposeEmail(notificationObjectType, actionType, user, additionalData);
                var mailConfig    = new MailMessageConfig()
                {
                    EmailBody    = emailComposer.Value,
                    EmailSubject = emailComposer.Key,
                    To           = new string[] { user.Email }
                };

                var smtp = new SmtpSender(mailConfig);
                status = smtp.SendMail();
            }
            return(status);
        }
 private async Task OnSuccess(HttpContext context, MailMessageStatus status)
 {
     context.Response.StatusCode  = 200;
     context.Response.ContentType = "application/json";
     await context.Response.WriteAsync(JsonSerializer.Serialize(status, _jsonOptions));
 }
예제 #5
0
        public void ProcessQueue()
        {
            // using (var client = new SmtpClient(new ProtocolLogger ("smtp.log")))
            using (var client = new SmtpClient())
            {
                foreach (var source in _queue.GetConsumingEnumerable())
                {
                    var status = new MailMessageStatus
                    {
                        ReferenceId = source.ReferenceId,
                        MessageId   = source.MessageId
                    };

                    if (!client.IsConnected)
                    {
                        try
                        {
                            _logger.LogDebug("Items in queue; connecting smtp client to [{0}].", _options.Host);
                            client.Connect(_options.Host, _options.Port); //, SecureSocketOptions.Auto);
                            client.AuthenticationMechanisms.Remove("XOAUTH2");
                            if (_options.User.HasValue() && _options.Password.HasValue())
                            {
                                client.Authenticate(_options.User, _options.Password);
                            }
                        }
                        catch (Exception ex)
                        {
                            status.Status = MessageStatus.failure.ToString();
                            _logger.LogError("Failed to connect to smtp server [{0}]. {1}", _options.Host, ex.Message);
                        }
                    }

                    if (client.IsConnected)
                    {
                        if (!source.From.HasValue())
                        {
                            source.From = _options.Sender;
                        }

                        source.Cc += $";{_options.CcRecipients}";

                        source.Bcc += $";{_options.BccRecipients}";

                        if (source.BccSender)
                        {
                            source.Bcc += $";{source.From}";
                        }

                        var message = source.ToMimeMessage();

                        try
                        {
                            client.Send(FormatOptions.Default, message);
                            status.Status = MessageStatus.success.ToString();
                            _logger.LogInformation(logMsg, source.To, source.ClientName, "succeeded", "");
                        }
                        catch (Exception ex)
                        {
                            status.Status = MessageStatus.failure.ToString();
                            _logger.LogError(logMsg, source.To, source.ClientName, "failed", ex.Message);
                        }
                    }

                    status.Timestamp = DateTime.UtcNow;

                    _cache.SetString(
                        status.ReferenceId,
                        JsonSerializer.Serialize(status),
                        _cacheOptions
                        );

                    if (_queue.Count == 0 && client.IsConnected)
                    {
                        client.Disconnect(true);
                        _logger.LogDebug("Queue empty; disconnected smtp client.");
                    }
                }
            }
        }