Exemple #1
0
        public static EmailMessageModel ConstructAdoptedEmail(Adopter adopter)
        {
            var content = "";
            var sender  = new EmailAddressModel
            {
                Name    = "Šaponja",
                Address = "*****@*****.**"
            };

            var receiver = new EmailAddressModel()
            {
                Name    = adopter.FirstName,
                Address = adopter.Email
            };

            var email = new EmailMessageModel
            {
                Subject         = "Odabrani ste kao udomitelj",
                SenderAddress   = sender,
                ReceiverAddress = receiver,
                Content         = content
            };

            return(email);
        }
        public IActionResult SendMail([FromServices] IEmailConfiguration myEmailConfig, [FromForm] string messageContent, [FromForm] string messageSubject, [FromForm] string replyAddress)
        {
            var myEmailService = new EmailService(myEmailConfig);

            var recipient = new EmailAddressModel
            {
                Address = "*****@*****.**"
            };

            var sender = new EmailAddressModel
            {
                Address = "*****@*****.**"
            };

            var externalSender = new EmailAddressModel
            {
                Address = replyAddress
            };

            var myMessage = new EmailMessageModel();

            myMessage.ToAddresses.Add(recipient);
            myMessage.FromAddresses.Add(sender);

            myMessage.Subject = messageSubject;
            myMessage.Content = messageContent + " sent from: " + replyAddress;
            myMessage.FromAddresses.Add(externalSender);

            myEmailService.Send(myMessage);

            return(View());
        }
Exemple #3
0
        public ResponseResult SendEmail(EmailMessageModel emailModel)
        {
            var message = new MimeMessage();

            message.To.Add(new MailboxAddress(emailModel.ReceiverAddress.Name, emailModel.ReceiverAddress.Address));
            message.From.Add(new MailboxAddress(emailModel.SenderAddress.Name, emailModel.SenderAddress.Address));
            message.Subject = emailModel.Subject;

            var builder = new BodyBuilder();

            if (emailModel.AttachmentPath != null)
            {
                var serverPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", emailModel.AttachmentPath);
                builder.Attachments.Add(serverPath);
            }
            builder.HtmlBody = emailModel.Content;

            message.Body = builder.ToMessageBody();

            using var emailClient = new SmtpClient();
            emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, false);
            emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
            emailClient.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);

            emailClient.Send(message);
            emailClient.Disconnect(true);

            return(ResponseResult.Ok);
        }
        private void NotifyAccordingToNotificationType(Guid notificationBatchGuid, string notificationTypeName)
        {
            var notificationMessages =
                _notificationMessageService.GetByNotificationBatchIdAndNotificationType(notificationBatchGuid, notificationTypeName);

            var notifyMessage =
                _notificationMessageService.GetByNotificationBatchIdAndNotificationType(notificationBatchGuid, notificationTypeName).FirstOrDefault();

            List <string> emailList = new List <string>();

            foreach (var notificationMessage in notificationMessages)
            {
                var ob = _userService.GetUserByUserGuid(notificationMessage.UserGuid).WorkEmail;
                emailList.Add(ob);
            }
            EmailMessageModel usersToNotifyWithTemplate = new EmailMessageModel()
            {
                NotificationMessageGuid = notifyMessage.NotificationMessageGuid,
                Message           = notifyMessage.Message,
                Subjects          = notifyMessage.Subject,
                Status            = notifyMessage.Status,
                AdditionalMessage = notifyMessage.AdditionalMessage,
                WorkEmail         = string.Join(",", emailList),
                Displayname       = _userService.GetUserByUserGuid(notifyMessage.UserGuid).DisplayName
            };

            /*
             * todo   make method GetNotificationTypeByNotificationBatchId -
             * todo   to compare either Email Notification or SMS Notification in future..
             */

            _emailSender.SendEmailAsync(usersToNotifyWithTemplate.WorkEmail, usersToNotifyWithTemplate.Displayname, usersToNotifyWithTemplate.Subjects,
                                        usersToNotifyWithTemplate.Message);
        }
Exemple #5
0
 private void SendEmail(EmailMessageModel model)
 {
     if (model != null && !String.IsNullOrWhiteSpace(model.Recipients))
     {
         _eventBusPublisher.Publish(model, EmailMessageModel.EMAIL_QUEUE_NAME);
     }
 }
        public void SendLoginDetails(LoginDetailsEmailModel model)
        {
            var templateFilePath = Directory.GetCurrentDirectory()
                                   + Path.DirectorySeparatorChar.ToString()
                                   + "Templates"
                                   + Path.DirectorySeparatorChar.ToString()
                                   + "EmailTemplates"
                                   + Path.DirectorySeparatorChar.ToString()
                                   + "LoginDetailsEmail.html";

            var builder = new BodyBuilder();

            using (StreamReader SourceReader = File.OpenText(templateFilePath))
            {
                builder.HtmlBody = SourceReader.ReadToEnd();
            }

            string messageBody = string.Format(builder.HtmlBody, model.ReceiverName, model.EmailId, model.Password);

            EmailMessageModel messageModel = new EmailMessageModel();

            messageModel.EmailBody = messageBody;
            messageModel.Subject   = model.Subject;
            messageModel.To        = model.ReceiverEmail;

            this.emailSender.SendEmail(messageModel);
        }
Exemple #7
0
        public void Invoke_ValidData_AddsEmailMessageToDatabaseWithCorrectValues()
        {
            // prepare
            var emailMessage = new EmailMessageModel
            {
                From      = "*****@*****.**",
                Recipient = "*****@*****.**",
                Subject   = "subject",
                Message   = "message"
            };

            EmailMessage emailMessageFromDb           = null;
            var          mockedEmailMessageRepository = new Mock <IEmailRepository>();

            mockedEmailMessageRepository.Setup(r => r.Add(It.IsAny <EmailMessage>()))
            .Callback <EmailMessage>(u => emailMessageFromDb = u);
            var mockedUnitOfWork = new Mock <IUnitOfWork>();

            var action = new AddNewEmailMessage(mockedEmailMessageRepository.Object, mockedUnitOfWork.Object);

            // action
            var result = action.Invoke(emailMessage);

            // assert
            Assert.True(result);
            Assert.Equal("*****@*****.**", emailMessageFromDb.From);
            Assert.Equal("*****@*****.**", emailMessageFromDb.Recipient);
            Assert.Equal("subject", emailMessageFromDb.Subject);
            Assert.Equal("message", emailMessageFromDb.Message);
            Assert.Equal(0, emailMessageFromDb.FailureCount);

            mockedEmailMessageRepository.Verify(r => r.Add(It.IsAny <EmailMessage>()), Times.Once);
            mockedUnitOfWork.Verify(r => r.Save(), Times.Once);
        }
Exemple #8
0
        public static EmailMessageModel ConstructDocumentationEmail(Adopter adopter)
        {
            var content = "";

            var sender = new EmailAddressModel
            {
                Name    = "Šaponja",
                Address = "*****@*****.**"
            };

            var receiver = new EmailAddressModel()
            {
                Name    = adopter.FirstName,
                Address = adopter.Email
            };

            var email = new EmailMessageModel
            {
                Subject         = $"Dokumentacija za{adopter.Animal.Name}",
                SenderAddress   = sender,
                ReceiverAddress = receiver,
                Content         = content,
                AttachmentPath  = adopter.Animal.Shelter.DocumentationFilePath
            };

            return(email);
        }
        public async Task Consume(ConsumeContext <ISendEmailCommand> context)
        {
            var sendEmailCommand = context.Message;
            var message          = new EmailMessageModel();

            if (sendEmailCommand.Attachment)
            {
                var attach = await _emailMessageService.SendProductDetailsAsEmail(sendEmailCommand.CompanyId, sendEmailCommand.CatalogId);

                var messageModel = new EmailMessageModel
                {
                    To         = sendEmailCommand.To,
                    Subject    = sendEmailCommand.Subject,
                    Body       = sendEmailCommand.Body,
                    attachment = attach,
                };
                message = messageModel;
            }
            else
            {
                var emailData = new EmailTemplatePlaceholdersGeneratorRequestModel
                {
                    EmailTemplateType   = sendEmailCommand.EmailTemplateType,
                    UserName            = sendEmailCommand.UserName,
                    CompanyId           = sendEmailCommand.CompanyId,
                    Password            = sendEmailCommand.Password,
                    TempResetLink       = sendEmailCommand.TempResetLink,
                    Domain              = sendEmailCommand.Domain,
                    TxtRecord           = sendEmailCommand.TxtRecord,
                    Report              = sendEmailCommand.Report,
                    CustomSecurePanelId = sendEmailCommand.CustomSecureCompanyId,
                };

                var template = _emailMessageService.GetEmailTemplate(emailData);

                var MessageModel = new EmailMessageModel
                {
                    To             = sendEmailCommand.To,
                    Subject        = template.Subject,
                    Body           = template.Body,
                    EmailMediaType = EmailMediaType.Html,
                    BCC            = sendEmailCommand.BCC
                };
                message = MessageModel;
            }
            // Required fields: EmailTemplateType and UserName or ComapnyId
            var sendEmailService = Settings.IoC.GetContainer().Resolve <ISendEmailService>();

            this.Log().Info($"Sending email {sendEmailCommand.EmailTemplateType.ToString()} to {sendEmailCommand.To}");

            sendEmailService.SendEmail(message);

            foreach (var recipient in sendEmailCommand.Recipients)
            {
                message.To = recipient;
                sendEmailService.SendEmail(message);
            }

            await Task.FromResult(context.Message);
        }
Exemple #10
0
        /// <summary>
        /// Sending email with Mail message and attachment
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool SendEmail(EmailMessageModel message)
        {
            SmtpClient client = new SmtpClient(_host);
            ILogger    logger = Log.ForContext <EmailHelper>();

            try
            {
                client.Send(message.ToMailMessage());
            }
            catch (SmtpException e)
            {
                logger.Error(e, "SMTPException while sending email.");

                return(false);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error while sending email.");

                return(false);
            }
            finally
            {
                if (client != null)
                {
                    client = null;
                }
            }

            return(true);
        }
Exemple #11
0
        public void SendEmail(EmailMessageModel emailMsg)
        {
            var    message       = new MimeMessage();
            string emailName     = _emailConfig.Value.Name;
            string emailUserName = _emailConfig.Value.UserName;
            string emailPassword = _emailConfig.Value.Password;

            message.From.Add(new MailboxAddress(emailName, emailUserName));
            message.To.Add(new MailboxAddress(emailMsg.ToName, emailMsg.ToEmailAddress));
            message.Subject = emailMsg.Subject;
            message.Body    = new TextPart("plain")
            {
                Text = emailMsg.Body
            };

            try
            {
                using var client = new SmtpClient();
                client.Connect("smtp.gmail.com", 587);

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(emailUserName, emailPassword);

                client.Send(message);
                client.Disconnect(true);
            }
            catch (Exception err)
            {
                Console.Write(err.Message, err.GetType());
            }
        }
        public void Send(EmailMessageModel emailMessage)
        {
            var message = new MimeMessage();

            message.To.Add(new MailboxAddress(emailMessage.Email));
            message.From.Add(new MailboxAddress("HomeSecurity", _emailConfiguration.SmtpAddress));

            message.Subject = emailMessage.Subject;
            //We will say we are sending HTML. But there are options for plaintext etc.
            message.Body = new TextPart(TextFormat.Html)
            {
                Text = emailMessage.Content
            };

            //Be careful that the SmtpClient class is the one from Mailkit not the framework!
            using (var emailClient = new SmtpClient())
            {
                //The last parameter here is to use SSL (Which you should!)
                emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, true);

                //Remove any OAuth functionality as we won't be using it.
                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                emailClient.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);

                emailClient.Send(message);

                emailClient.Disconnect(true);
            }
        }
 public ActionResponse Add(EmailMessageModel model)
 {
     using (var unitWork = new UnitOfWork(context))
     {
         ActionResponse response = new ActionResponse();
         try
         {
             var isEmailMessageCreated = unitWork.EmailMessagesRepository.GetOne(m => m.MessageType == model.MessageType);
             if (isEmailMessageCreated != null)
             {
                 isEmailMessageCreated.Message = model.Message;
                 unitWork.EmailMessagesRepository.Update(isEmailMessageCreated);
                 response.ReturnedId = isEmailMessageCreated.Id;
             }
             else
             {
                 var newEmailMessage = unitWork.EmailMessagesRepository.Insert(new EFEmailMessages()
                 {
                     MessageType   = model.MessageType,
                     Subject       = model.Subject,
                     Message       = model.Message,
                     FooterMessage = model.FooterMessage
                 });
                 response.ReturnedId = newEmailMessage.Id;
             }
             unitWork.Save();
         }
         catch (Exception ex)
         {
             response.Success = false;
             response.Message = ex.Message;
         }
         return(response);
     }
 }
Exemple #14
0
        public void ValidData_ModelAreCorrect()
        {
            // prepare
            const string from             = "from";
            const string recipient        = "recipient";
            const string subject          = "subject";
            const string message          = "message";
            const int    failureCount     = 5;
            const string failError        = "failError";
            const string failErrorMessage = "failErrorMessage";

            // action
            var action = new EmailMessageModel
            {
                From             = from,
                Recipient        = recipient,
                Subject          = subject,
                Message          = message,
                FailureCount     = failureCount,
                FailError        = failError,
                FailErrorMessage = failErrorMessage
            };

            // check
            Assert.Equal("from", action.From);
            Assert.Equal("recipient", action.Recipient);
            Assert.Equal("subject", action.Subject);
            Assert.Equal("message", action.Message);
            Assert.Equal(5, action.FailureCount);
            Assert.Equal("failError", action.FailError);
            Assert.Equal("failErrorMessage", action.FailErrorMessage);
        }
Exemple #15
0
        public async Task <string> SendEmail([FromForm] EmailMessageModel model)
        {
            EmailMessageModel emailMessage = new EmailMessageModel
            {
                Name       = model.Name,
                Email      = model.Email,
                Message    = model.Message,
                Attachment = model.Attachment
            };

            if (emailMessage.Attachment != null)
            {
                if (_fileInsider.IsFormatAllowed(emailMessage.Attachment))
                {
                    if (emailMessage.Attachment.Length > 10485760)
                    {
                        return("File size not supported.");
                    }
                }
                else
                {
                    return("File format not supported.");
                }
            }

            MailMessage message = new MailMessage();

            message.Body = $"<h2>Name: {emailMessage.Name}, Email: {emailMessage.Email}</h2><p>{emailMessage.Message}</p>";

            if (emailMessage.Attachment != null)
            {
                Attachment data = new Attachment(emailMessage.Attachment.OpenReadStream(), emailMessage.Attachment.FileName, emailMessage.Attachment.ContentType);
                message.Attachments.Add(data);
            }

            message.IsBodyHtml = true;
            message.From       = new MailAddress(_appSettings.EmailSenderAddress, _appSettings.EmailSenderName);
            message.To.Add(new MailAddress(_appSettings.EmailReceiverAddress));
            message.Subject = _appSettings.EmailSubject;

            using (var client = new SmtpClient(_appSettings.SMTPHost, int.Parse(_appSettings.SMTPPort)))
            {
                client.Credentials = new NetworkCredential(_appSettings.SMTPUsername, _appSettings.SMTPPassword);
                client.EnableSsl   = true;

                try
                {
                    await client.SendMailAsync(message);

                    return("Message successfully sent!");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"{nameof(SendEmail)} => FAIL with args: {model.Name} {model.Email} {model.Message} {model.Attachment.FileName} {model.Attachment.ContentType}");
                }

                return("Something went wrong. Try again!");
            }
        }
        public ActionResult List()
        {
            EmailMessageModel model = new EmailMessageModel();

            model.EmailMessages = _emailService.GetEmailMessages();

            return(View(model));
        }
Exemple #17
0
        public Clue Create(EmailMessageModel value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            return(this.Create(EntityType.Mail, value.Object.Id.UniqueId));
        }
        public ActionResult List(EmailMessageModel model)
        {
            if (ModelState.IsValid)
            {
                _emailService.ReceiveEmails(model.ServerAddress, model.ServerPort, model.Email, model.Password);
            }

            return(RedirectToAction("List"));
        }
        public OperationModel AddTransactionData(CollectionTransactionViewModel collectionTransactionViewModel)
        {
            try
            {
                OperationModel             operationModel             = new OperationModel();
                CollectionTransactionModel collectionTransactionModel = new CollectionTransactionModel();

                collectionTransactionModel.ApplicantName      = collectionTransactionViewModel.ApplicantName;
                collectionTransactionModel.MobileNumber       = collectionTransactionViewModel.MobileNumber;
                collectionTransactionModel.Address            = collectionTransactionViewModel.Address;
                collectionTransactionModel.AadhaarNumber      = collectionTransactionViewModel.AadhaarNumber;
                collectionTransactionModel.PanNumber          = collectionTransactionViewModel.PanNumber;
                collectionTransactionModel.ApplicantGSTNumber = collectionTransactionViewModel.ApplicantGSTNumber;
                collectionTransactionModel.TotalAmount        = collectionTransactionViewModel.TotalAmount;
                collectionTransactionModel.CreatedBy          = collectionTransactionViewModel.CreatedBy;
                collectionTransactionModel.TransactionId      = Guid.NewGuid().ToString().Trim();
                collectionTransactionModel.TransactionStatus  = (int)TransactionStatus.Pending;
                collectionTransactionModel.Remarks            = collectionTransactionViewModel.Remarks;
                collectionTransactionModel.DepartmentId       = collectionTransactionViewModel.DepartmentId;

                DataTable dataTable = new DataTable("dbo.TransactionServiceList");

                dataTable.Columns.Add("ServiceId", typeof(Int16));
                dataTable.Columns.Add("Rate", typeof(decimal));
                dataTable.Columns.Add("Quantity", typeof(Int16));
                dataTable.Columns.Add("Remarks", typeof(string));

                for (int i = 0; i < collectionTransactionViewModel.TransactionServiceModelList.Count; i++)
                {
                    DataRow dr = dataTable.NewRow();
                    dr["ServiceId"] = collectionTransactionViewModel.TransactionServiceModelList[i].ServiceId;
                    dr["Rate"]      = collectionTransactionViewModel.TransactionServiceModelList[i].Rate;
                    dr["Quantity"]  = collectionTransactionViewModel.TransactionServiceModelList[i].Quantity;
                    dr["Remarks"]   = collectionTransactionViewModel.TransactionServiceModelList[i].Remarks;
                    dataTable.Rows.Add(dr);
                }

                using (CollectionTransactionDB collectionTransactionDB = new CollectionTransactionDB())
                {
                    operationModel = collectionTransactionDB.AddTransactionData(collectionTransactionModel, dataTable);
                }
                if (operationModel.OperationStatus == (int)EnumModel.OperationStatus.Success)
                {
                    EmailMessageHelper emailMessageHelper = new EmailMessageHelper();
                    EmailMessageModel  emailMessageModel  = new EmailMessageModel();
                    emailMessageModel.ReceiverEmailAddress = collectionTransactionViewModel.EmailAddress;
                    emailMessageModel.ApplicantName        = collectionTransactionViewModel.ApplicantName;
                    emailMessageModel.TransactionId        = operationModel.OperationLogId;
                    emailMessageHelper.SendEmail(emailMessageModel);
                }
                return(operationModel);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public void SendEmail(EmailMessageModel mailMessage)
        {
            var message = BuildMessage(mailMessage);

            using (var smtp = GetSmtpClient())
            {
                smtp.Send(message);
            }
        }
        public void Send(EmailMessageModel model)
        {
            if (EmailConfig == null)
            {
                throw new InvalidOperationException("Invalid email configuration");
            }

            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(model.SenderName, model.From));
            message.To.Add(new MailboxAddress(model.RecipientName, model.To));
            message.ReplyTo.Add(new MailboxAddress(model.ReplyTo));
            message.Subject = model.Subject;

            foreach (string email in model.Cc)
            {
                message.Cc.Add(new MailboxAddress(email));
            }

            foreach (string email in model.Bcc)
            {
                message.Bcc.Add(new MailboxAddress(email));
            }

            var builder = new BodyBuilder();

            builder.HtmlBody = model.HtmlMessage;
            builder.TextBody = model.RawMessage;

            message.Body = builder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(EmailConfig.ServerName, EmailConfig.Port, false);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                client.Authenticate(EmailConfig.UserName, EmailConfig.Passwd);

                try
                {
                    WriteLine($"Sending message to: {model.RecipientName}<{model.To}>...");
                    client.Send(message);
                    client.Disconnect(true);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        private void SendEmail(EmailMessageModel model)
        {
            if (model == null)
            {
                return;
            }

            this.EmailService.SendEmail($"Demo-Tools: {model.Subject}", model.Body, model.Recipients);

            _logger.LogInformation($"Email sent to {model.Recipients}: {model.Subject}");
        }
Exemple #23
0
        public void SendEmail(EmailMessageModel emailMessageModel)
        {
            //Fetching Email Body Text from EmailTemplate File.
            string filePath = ConfigurationManager.AppSettings["TemplatePath"].ToString();
            // "D:\\Client_PGB\\TestProject\\CollectionManagement\\CollectionManagement.WebProject\\Template\\EmailTemplate.html";
            StreamReader str      = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(filePath));
            string       MailText = str.ReadToEnd();

            str.Close();

            //Repalce [newusername] = signup user name
            MailText = MailText.Replace("{UserName}", emailMessageModel.ApplicantName).Replace("{txnId}", emailMessageModel.TransactionId);

            string subject = "Welcome to Collection Management System";

            //Base class for sending email
            MailMessage _mailmsg = new MailMessage();

            //Make TRUE because our body text is html
            _mailmsg.IsBodyHtml = true;

            //Set From Email ID
            _mailmsg.From = new MailAddress(emailSender);

            //Set To Email ID
            _mailmsg.To.Add(emailMessageModel.ReceiverEmailAddress);

            //Set Subject
            _mailmsg.Subject = subject;

            //Set Body Text of Email
            _mailmsg.Body = MailText;


            //Now set your SMTP
            SmtpClient _smtp = new SmtpClient();

            //Set HOST server SMTP detail
            _smtp.Host = emailSenderHost;

            //Set PORT number of SMTP
            _smtp.Port = emailSenderPort;

            //Set SSL --> True / False
            _smtp.EnableSsl = emailIsSSL;

            //Set Sender UserEmailID, Password
            NetworkCredential _network = new NetworkCredential(emailSender, emailSenderPassword);

            _smtp.Credentials = _network;

            //Send Method will send your MailMessage create above.
            _smtp.Send(_mailmsg);
        }
        public async Task <bool> SendEmails(EmailMessageModel message, List <IEmailPersonalisation> personalisations)
        {
            if (!personalisations.Any())
            {
                return(false);
            }

            try
            {
                using (var context = DataContextFactory.CreateContext())
                {
                    var template = await context.EmailTemplates.FirstOrDefaultNoLockAsync(x => x.Type == message.EmailType);

                    if (template == null)
                    {
                        return(false);
                    }

                    if (string.IsNullOrEmpty(message.Subject))
                    {
                        message.Subject = template.Subject;
                    }

                    var body = string.Format(template.Template, message.BodyParameters).Replace("{{", "{").Replace("}}", "}");

                    var email = new SendGridMessage
                    {
                        From        = new EmailAddress(EmailFrom),
                        Subject     = message.Subject,
                        HtmlContent = body,
                        Headers     = new Dictionary <string, string> {
                            { "category", $"{message.EmailType} - {message.SystemIdentifier}" }
                        },
                        Personalizations = personalisations.Select(p => new Personalization
                        {
                            Bccs          = p.Bccs?.Select(e => new EmailAddress(e)).ToList(),
                            Ccs           = p.Ccs?.Select(e => new EmailAddress(e)).ToList(),
                            Substitutions = p.Substitutions,
                            Tos           = p.Tos?.Select(e => new EmailAddress(e)).ToList(),
                            Subject       = string.IsNullOrWhiteSpace(p.Subject) ? message.Subject : p.Subject
                        }).ToList()
                    };

                    var response = await _sendGridClient.SendEmailAsync(email).ConfigureAwait(false);

                    return(response.StatusCode == HttpStatusCode.Accepted);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public async Task <IWriterResult> RejectUser(string currentAdminId, int verificationId, string reason)
        {
            string            userName;
            EmailMessageModel emailModel;

            using (var context = DataContextFactory.CreateContext())
            {
                var userVerification = await context.UserVerification
                                       .Include(uv => uv.User)
                                       .Where(uv => uv.Id == verificationId)
                                       .FirstOrDefaultNoLockAsync();

                if (userVerification == null)
                {
                    return(new WriterResult(false, "User Verification Entity not found"));
                }

                var user = userVerification.User;

                if (userVerification.User.VerificationLevel != VerificationLevel.Level2Pending)
                {
                    return(new WriterResult(false, "User Verification level not at Level 2 Pending"));
                }


                var rejectedUserEntity = UserVerificationReject.CreateFrom(userVerification);
                rejectedUserEntity.RejectReason = reason;
                context.UserVerificationReject.Add(rejectedUserEntity);

                user.VerificationLevel = VerificationLevel.Level1;

                context.UserVerification.Remove(userVerification);
                context.LogActivity(currentAdminId, $"Rejected User Verification for {userVerification.FirstName} {userVerification.LastName}. Reason: {reason}");

                await context.SaveChangesAsync();

                var emailParameters = new List <object> {
                    user.UserName, reason
                };
                emailModel = new EmailMessageModel
                {
                    BodyParameters = emailParameters.ToArray(),
                    Destination    = user.Email,
                    EmailType      = EmailTemplateType.UserAccountRejected
                };

                userName = user.UserName;
            }

            await EmailService.SendEmail(emailModel);

            return(new WriterResult(true, $"User {userName} Rejected - Email sent"));
        }
Exemple #26
0
        public async Task Send(MailConfigType type, EmailMessageModel message)
        {
            var email = new MimeMessage();

            email.To.AddRange(message.Recipients.Select(r => new MailboxAddress(r.Name, r.Address)));
            email.From.AddRange(
                message.From.Select(a => new MailboxAddress(a.Name, a.Address))
                );
            email.Sender = new MailboxAddress(message.SenderAddress);
            if (message.Cc != null)
            {
                email.Cc.AddRange(message.Cc.Select(r => new MailboxAddress(r.Name, r.Address)));
            }
            if (message.Bcc != null)
            {
                email.Bcc.AddRange(message.Bcc.Select(r => new MailboxAddress(r.Name, r.Address)));
            }
            email.Subject = message.Subject;

            var bodyBuilder = new BodyBuilder();

            bodyBuilder.TextBody = message.Content;
            email.Body           = bodyBuilder.ToMessageBody();

            switch (type)
            {
            case MailConfigType.SMTP:
                using (var client = new SmtpClient())
                {
                    var config = _config.SMTP;
                    client.Connect(config.ServerName, config.Port, config.IsUsingSSL);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(config.User, config.Password);
                    await client.SendAsync(email);

                    client.Disconnect(true);
                }
                break;

            case MailConfigType.POP3:
                throw new NotImplementedException("POP3 not implemented!");
                break;

            case MailConfigType.IMAP:
                throw new NotImplementedException("IMAP not implemented!");
                break;

            default:
                throw new ArgumentException("Wrong mail protocol!");
                break;
            }
        }
        /// <summary>
        /// Composes the message.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <returns></returns>
        private MailMessage ComposeMessage(EmailMessageModel email)
        {
            var message = new MailMessage();

            //Add sender address
            message.From = new MailAddress(email.From.EmailAddress, email.From.DisplayName);

            //Add recipient address
            email.To.ForEach(delegate(EmailAddressModel to)
            {
                message.To.Add(new MailAddress(to.EmailAddress, to.DisplayName));
            });

            //Add CC
            if (email.CC != null)
            {
                email.CC.ForEach(delegate(EmailAddressModel cc)
                {
                    message.CC.Add(new MailAddress(cc.EmailAddress, cc.DisplayName));
                });
            }

            //Add BCC
            if (email.BCC != null)
            {
                email.BCC.ForEach(delegate(EmailAddressModel bcc)
                {
                    message.Bcc.Add(new MailAddress(bcc.EmailAddress, bcc.DisplayName));
                });
            }

            message.Subject    = email.Subject;
            message.Body       = email.Body;
            message.IsBodyHtml = email.IsBodyHtml;

            //create attachment for this e-mail message
            if (email.Attachments != null)
            {
                email.Attachments.ForEach(delegate(EmailAttachmentModel emailAttachment)
                {
                    var attachment = new Attachment(new MemoryStream(emailAttachment.AttachmentContent), emailAttachment.AttachmentName);

                    if (!String.IsNullOrEmpty(emailAttachment.AttachmentName))
                    {
                        attachment.Name = emailAttachment.AttachmentName;
                    }
                    message.Attachments.Add(attachment);
                });
            }

            return(message);
        }
        public async Task <IWriterResult> AcceptUser(int verificationId, string currentAdminId)
        {
            EmailMessageModel emailModel;
            string            userName;
            string            userId;

            using (var context = DataContextFactory.CreateContext())
            {
                var userVerification = await context.UserVerification
                                       .Include(uv => uv.User)
                                       .Where(uv => uv.Id == verificationId)
                                       .FirstOrDefaultNoLockAsync();

                if (userVerification == null)
                {
                    return(new WriterResult(false, "User Verification Entity not found"));
                }

                var user = userVerification.User;

                if (userVerification.User.VerificationLevel != VerificationLevel.Level2Pending)
                {
                    return(new WriterResult(false, "User Verification level not at Level 2 Pending"));
                }

                userVerification.ApprovedBy = currentAdminId;
                userVerification.Approved   = DateTime.UtcNow;
                user.VerificationLevel      = VerificationLevel.Level2;

                var emailParameters = new List <object> {
                    user.UserName
                };

                emailModel = new EmailMessageModel
                {
                    BodyParameters = emailParameters.ToArray(),
                    Destination    = user.Email,
                    EmailType      = EmailTemplateType.UserAccountVerified
                };

                userId   = user.Id;
                userName = user.UserName;
                context.LogActivity(currentAdminId, $"Accepted User Verification for {userVerification.FirstName} {userVerification.LastName}.");
                await context.SaveChangesAsync();
            }

            await UserSyncService.SyncUser(userId);

            await EmailService.SendEmail(emailModel);

            return(new WriterResult(true, $"User {userName} Verified - Email sent."));
        }
        public bool Invoke(EmailMessageModel email)
        {
            if (!email.IsValid())
            {
                return(false);
            }

            var dbMessage = AutoMapper.Mapper.Map <EmailMessage>(email);

            emailRepository.Add(dbMessage);
            _unitOfWork.Save();

            return(true);
        }
Exemple #30
0
        public IActionResult Put(int id, [FromBody] EmailMessageModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var response = emailMessageService.Update(id, model);

            if (!response.Success)
            {
                return(BadRequest(response.Message));
            }
            return(Ok(true));
        }