Пример #1
0
 public static EmailMessagePrototype CreateNewEmailFromTemplate(MailNotificationModel notificationModel)
 {
     return(CreateNewEmail()
            .SetHeader(notificationModel.Meta)
            .SetSubject(notificationModel.Subject)
            .SetReceivers(notificationModel.ToAddresses)
            .SetBccAddresses(notificationModel.BccAddresses)
            .SetCcAddresses(notificationModel.CcAddresses)
            .SetFromName(notificationModel.FromEmail, notificationModel.FromName)
            .SetBody(notificationModel.Body, notificationModel.Html, notificationModel.Args, notificationModel.TemplatePath)
            .SetFileAttachment(notificationModel.Attachments));
 }
Пример #2
0
        // private async Task<Response> SendEmail(MailNotificationModel message)
        // {
        //     //TODO: maybe change implementation of sending email
        //     try
        //     {
        //         message.FromEmail = _smtpCredentials.Email;
        //         message.FromName ??= _smtpCredentials.FromName;
        //         using (var client = new SmtpClient(_smtpCredentials.Server, _smtpCredentials.Port))
        //         {
        //             client.UseDefaultCredentials = false;
        //             client.Credentials = new NetworkCredential(_smtpCredentials.Email, _smtpCredentials.Password);
        //             client.EnableSsl = _smtpCredentials.UseSsl;
        //             using var emailMessage = EmailMessagePrototype.CreateNewEmailFromTemplate(message);
        //             await client.SendMailAsync(emailMessage.GetMessage());
        //         }
        //     }
        //     catch (Exception e)
        //     {
        //         _logger.LogError(e, "Can't send emails");
        //         return new ErrorResponse
        //         {
        //             Message = e.Message
        //         };
        //     }
        //
        //     _logger.LogInformation("Emails send success");
        //     return new Response();
        // }

        private async Task <Response> SendEmail(MailNotificationModel baseMessage)
        {
            try
            {
                var apiKey = _smtpCredentials.SendGridApiKey;
                var client = new SendGridClient(apiKey);

                baseMessage.FromEmail = _smtpCredentials.Email;
                baseMessage.FromName ??= _smtpCredentials.FromName;
                using var emailMessage = EmailMessagePrototype.CreateNewEmailFromTemplate(baseMessage);
                var message = emailMessage.GetMessage();

                var messageSendGrid = new SendGridMessage
                {
                    From             = new EmailAddress(_smtpCredentials.Email, _smtpCredentials.FromName),
                    HtmlContent      = message.Body,
                    PlainTextContent = message.Body,
                    Subject          = message.Subject,
                    TemplateId       = null
                };

                foreach (var address in message.To)
                {
                    messageSendGrid.AddTo(address.Address);
                }

                var response = await client.SendEmailAsync(messageSendGrid);

                _logger.LogInformation($"Email sending status: {response.StatusCode}");

                var rawResponse = await response.Body.ReadAsStringAsync();

                _logger.LogInformation($"SendGridResponse: {rawResponse}");

                if (response.StatusCode != HttpStatusCode.Accepted)
                {
                    throw new Exception(rawResponse);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Can't send emails using SendGrid");
                return(new ErrorResponse
                {
                    Message = e.Message
                });
            }
            return(new Response());
        }
Пример #3
0
        public async Task <Response> SendEmail(EmailMessageDTO message)
        {
            var templatePath = $"{_fileDirectoryPath.EmailTemplatePath}/{message.TemplateId}.html";

            var mailNotificationModel = new MailNotificationModel
            {
                Body         = message.Body,
                Html         = message.Html,
                Subject      = message.Subject,
                Args         = message.Args,
                TemplatePath = message.TemplateId != null
                    ? $"{_fileDirectoryPath.EmailTemplatePath}/{message.TemplateId}.html"
                    : null,
                ToAddresses = message.ToEmails,
                FromName    = message.FromName
            };

            return(await SendEmail(mailNotificationModel));
        }
 public static NotificationProvider UseSparkPostEmailProvider(this NotificationProvider provider, MailNotificationModel model)
 {
     provider.NotificationService = new SparkPostNotificationService(model);
     return(provider);
 }
Пример #5
0
 public SparkPostNotificationService(MailNotificationModel model)
 {
     mailNotificationModel = model;
 }
Пример #6
0
        public async Task Send(MailNotificationModel parameters)
        {
            var hostName = configuration.GetSection("AppSettings").GetSection("Mail_HostName").Value;
            var user     = configuration.GetSection("AppSettings").GetSection("Mail_User").Value;
            var pass     = configuration.GetSection("AppSettings").GetSection("Mail_Pass").Value;
            var endpoint = configuration.GetSection("AppSettings").GetSection("Mail_Endpoint").Value;

            MailDispatcher.ClientMessage mailClient = new MailDispatcher.ClientMessage();
            mailClient.message         = new MailDispatcher.MessageModel();
            mailClient.message.To      = parameters.to;
            mailClient.message.CC      = parameters.cc ?? string.Empty;
            mailClient.message.Subject = parameters.subject;
            mailClient.message.Body    = parameters.body;

            if (parameters.attachments != null && parameters.attachments.Count > 0)
            {
                List <MailDispatcher.MessageAttachments> attachments = new List <MailDispatcher.MessageAttachments>();
                foreach (var item in parameters.attachments)
                {
                    MailDispatcher.MessageAttachments newAttachment = new MailDispatcher.MessageAttachments();
                    newAttachment.Content   = item.file.ToArray();
                    newAttachment.extension = item.extension;
                    newAttachment.name      = item.fileName + " " + DateTime.Now.ToString("dd-MM-yyyy");
                    item.file.Dispose();
                    attachments.Add(newAttachment);
                }
                mailClient.message.MessageAttachments = (attachments != null && attachments.Count > 0) ? attachments.ToArray() : null;
            }

            mailClient.message.UserCreated = hostName;
            mailClient.message.IsHtmlBody  = true;
            mailClient.message.NameClient  = hostName;
            mailClient.message.IdClient    = 1;

            var Binding  = GetBindingForEndpoint();
            var Endpoint = new EndpointAddress(endpoint);

            MailDispatcher.QueueClient mailService = new MailDispatcher.QueueClient(Binding, Endpoint);
            mailService.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
            {
                CertificateValidationMode = X509CertificateValidationMode.None,
                RevocationMode            = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck
            };

            mailService.ClientCredentials.UserName.UserName = user;
            mailService.ClientCredentials.UserName.Password = pass;

            Task <MailDispatcher.ClientMessage> mailDispatcherRequest;

            using (OperationContextScope scope = new OperationContextScope(mailService.InnerChannel))
            {
                string credentials = EncodeBasicAuthenticationCredentials(user, pass);
                HttpRequestMessageProperty request = new HttpRequestMessageProperty();
                request.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + credentials;

                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = request;
                mailDispatcherRequest = mailService.CreateMessageAsync(mailClient);
            }

            mailClient = await mailDispatcherRequest;
            if (!mailClient.Success)
            {
                throw new Exception(mailClient.Error);
            }
        }