예제 #1
0
        public bool SendSupportEmail(
            string fromEmail,
            string toEmail,
            string fullame,
            string username,
            string message)
        {
            SendGridHelper emailhelper = new SendGridHelper();
            SendGridModel  emailmodel  = new SendGridModel();

            var From = new Recipient
            {
                Email = fromEmail,
                Name  = fromEmail
            };

            emailmodel.From = From;

            var To = new Recipient
            {
                Email = toEmail,
                Name  = toEmail
            };

            emailmodel.To.Add(To);

            var Bcc = new Recipient
            {
                Email = "*****@*****.**",
                Name  = "*****@*****.**"
            };

            emailmodel.Bcc.Add(Bcc);

            /*Uncomment if need to attach single or multiple file*/
            //Attachment attachment = new Attachment(@"C:\2BInteractive\Docs\FTPAcct.txt");
            //emailmodel.Attachment.Add(attachment);

            var subject = @"CISELECT – Support Request";

            var body = "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>Support request was submitted on <strong>" + System.DateTime.Now.ToString("yyyy-MM-dd") + "</strong>.</span></p>";

            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'>  <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>User:</span></p>";
            body += string.Format("<span style='font-family:arial,Helvetica,sans-serif;font-size:13px'><strong>{0}</strong> (<strong>{1}</strong>)</span>", fullame, username);
            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'>  <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'><strong>" + toEmail + "</strong></span></p>";
            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'>  <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>Support Message:</span></p>";
            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'>  <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'> <strong>" + message + "</strong> </span></p>";
            DateTime dateTime = DateTime.UtcNow.Date;

            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'><em>This e-mail was sent on by the CISELECT application.  </em></span></p>";
            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><img src=\"http://tierracreative.clientpreview.agency/Images/cis-logo.png\" width=\"240\" height=\"60\"></p>";

            emailmodel.Subject    = subject;
            emailmodel.Body       = body;
            emailmodel.IsBodyHtml = true;

            var success = emailhelper.SendEmail(emailmodel);

            return(true);
        }
 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());
         }
     });
 }
예제 #3
0
        public async Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.
            var helper = new SendGridHelper();

            await helper.SendMail(message.Subject, message.Destination, message.Body);
        }
예제 #4
0
        public async void SendEmailReturnsSuccessResponse()
        {
            // Arrange
            var emailRequest = new EmailRequest();

            emailRequest.To        = "*****@*****.**";
            emailRequest.To_name   = "John Doe";
            emailRequest.From      = "*****@*****.**";
            emailRequest.From_name = "Jane Doe";
            emailRequest.Subject   = "Your Bill";
            emailRequest.Body      = "$100";


            //expectedResponse.Content //@"{StatusCode: 400, ReasonPhrase: 'BAD REQUEST', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:{Date: Wed, 05 Feb 2020 02:42:25 GMTServer: nginxConnection: keep-aliveContent-Type: application/jsonContent-Length: 157}}";
            var mailGunHelper       = new SendGridHelper();
            var mockResponseFromApi = JsonConvert.SerializeObject(new { id = "1234", message = "Message sent succesfully" });
            var expectedResponse    = new SendEmailResponse(true, "Email queued and will be sent shortly");

            var mockMessageHandler = new MockHttpMessageHandler(mockResponseFromApi, HttpStatusCode.OK);
            var httpClient         = new HttpClient(mockMessageHandler);

            // Act
            var actualResponse = await mailGunHelper.SendEmail(httpClient, emailRequest);

            // Assert
            Assert.Equal(expectedResponse.IsEmailSent, actualResponse.IsEmailSent);
            Assert.Equal(expectedResponse.Message, actualResponse.Message);
        }
예제 #5
0
        public void ResetPasswordShouldReturnBadRequestWhenGenerateAndSendIsFailed()
        {
            const string code     = "token";
            const string password = "******";
            Guid         userId   = Guid.NewGuid();

            var request = new ResetPasswordRequest
            {
                Code     = code,
                Password = password,
                UserId   = userId
            };

            var user     = new User();
            var response = SendGridHelper.GetEmptyResponse(System.Net.HttpStatusCode.BadRequest);

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.FindByIdAsync(userId))
            .ReturnsAsync(user);

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.ResetPasswordAsync(user, code, password))
            .ReturnsAsync(IdentityResult.Failed());

            var controller = _mock.Create <AuthController>();

            var expected = new BadRequestException("TOKEN_IS_INVALID");

            ExceptionAssert.ThrowsAsync(expected, () => controller.ResetPassword(request));
        }
예제 #6
0
        public async Task ForgotPasswordShouldReturnBadRequestWhenUserIsNotFound()
        {
            const string email           = "[email protected]";
            const string validationToken = "validation token";

            var request = new ForgotPasswordRequest
            {
                Email           = email,
                ValidationToken = validationToken
            };

            var response = SendGridHelper.GetEmptyResponse(System.Net.HttpStatusCode.Accepted);

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.FindByEmailAsync(email))
            .ReturnsAsync(null as User);

            _mock.Mock <ICaptchaValidationService>()
            .Setup(provider => provider.IsValidAsync(validationToken))
            .ReturnsAsync(true);

            var controller = _mock.Create <AuthController>();
            var actual     = await controller.ForgotPassword(request);

            var expected = new BadRequestObjectResult("USER_NOT_FOUND");

            ContentAssert.AreEqual(expected, actual);
        }
        public void ShouldThrowCanNotSendEmailException()
        {
            var user = new User()
            {
                Id    = Guid.NewGuid(),
                Email = "*****@*****.**"
            };
            var link      = "link";
            var clientUrl = "url";
            var subject   = "subject";
            var body      = "body";
            var token     = "token";

            var response = SendGridHelper.GetEmptyResponse(System.Net.HttpStatusCode.BadRequest);

            _mock.Mock <IClientUriService>()
            .Setup(x => x.BuildUri(clientUrl, new NameValueCollection()
            {
                { "userId", user.Id.ToString() },
                { "code", token },
            }))
            .Returns(link);

            _mock.Mock <IEmailService>()
            .Setup(x => x.SendAsync(It.Is <SendSingleEmailRequest>(request => request.Email == user.Email && request.Subject == subject && request.Content == body)))
            .ReturnsAsync(response);

            var expected = new CanNotSendEmailException(response.StatusCode.ToString());

            ExceptionAssert.ThrowsAsync(expected, () => _service.GenerateAndSendTokenAsync(user, token, clientUrl, subject, body));
        }
        public async Task ShouldGenerateAndSendPasswordResetToken()
        {
            var user = new User()
            {
                Id    = Guid.NewGuid(),
                Email = "*****@*****.**"
            };
            var link      = "link";
            var clientUrl = "url";
            var subject   = "subject";
            var body      = "body";
            var token     = "token";

            var response = SendGridHelper.GetEmptyResponse(System.Net.HttpStatusCode.Accepted);

            _mock.Mock <IClientUriService>()
            .Setup(x => x.BuildUri(clientUrl, new NameValueCollection()
            {
                { "userId", user.Id.ToString() },
                { "code", token },
            }))
            .Returns(link);

            _mock.Mock <IEmailService>()
            .Setup(x => x.SendAsync(It.Is <SendSingleEmailRequest>(request => request.Email == user.Email && request.Subject == subject && request.Content == body)))
            .ReturnsAsync(response);

            await _service.GenerateAndSendTokenAsync(user, token, clientUrl, subject, body);

            _mock.Mock <IEmailService>()
            .Verify(x => x.SendAsync(It.Is <SendSingleEmailRequest>(request => request.Email == user.Email && request.Subject == subject && request.Content == body)));
        }
        public void send_email_with_no_recipients()
        {
            var email = new SendGridHelper();
            var response = email.Send(new List<string>(), "subject", "body");

            Assert.IsFalse(response.Success);
            Assert.AreEqual("Please add at least one recipient to the email.", response.ErrorMessages.Single());
        }
        public HttpResponseMessage RoadZenResetPassword(LoginRequest passwordRequest)
        {
            Services.Log.Info("RoadZen Password Reset Request from Phone# [" + passwordRequest.Phone + "]");

            stranddContext context     = new stranddContext();
            Account        useraccount = context.Accounts.Where(a => a.Phone == passwordRequest.Phone).SingleOrDefault();

            if (useraccount != null)
            {
                if (useraccount.ProviderUserID.Substring(0, 7) != "RoadZen")
                {
                    string responseText = "Phone# Registered with Google";
                    Services.Log.Warn(responseText);
                    return(this.Request.CreateResponse(HttpStatusCode.BadRequest, WebConfigurationManager.AppSettings["RZ_MobileClientUserWarningPrefix"] + responseText));
                }
                else
                {
                    //Generate random characters from GUID
                    string newPassword = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 8);

                    //Encrypt new Password
                    byte[] salt = RoadZenSecurityUtils.generateSalt();
                    useraccount.Salt = salt;

                    useraccount.SaltedAndHashedPassword = RoadZenSecurityUtils.hash(newPassword, salt);
                    Services.Log.Info("Password for Phone# [" + passwordRequest.Phone + "] Reset & Saved");

                    //Save Encrypted Password
                    context.SaveChanges();

                    //Prepare SendGrid Mail
                    SendGridMessage resetEmail = new SendGridMessage();

                    resetEmail.From = SendGridHelper.GetAppFrom();
                    resetEmail.AddTo(useraccount.Email);
                    resetEmail.Subject = "StrandD Password Reset";
                    resetEmail.Html    = "<h3>New Password</h3><p>" + newPassword + "</p>";
                    resetEmail.Text    = "New Password: "******"New Password Email Sent to [" + useraccount.Email + "]";
                    Services.Log.Info(responseText);
                    return(this.Request.CreateResponse(HttpStatusCode.OK, responseText));
                }
            }
            else
            {
                string responseText = "Phone Number Not Registered";
                Services.Log.Warn(responseText);
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest, WebConfigurationManager.AppSettings["RZ_MobileClientUserWarningPrefix"] + responseText));
            }
        }
예제 #11
0
        public bool SendChangePasswordEmail(
            string fromEmail,
            string toEmail,
            string username)
        {
            SendGridHelper emailhelper = new SendGridHelper();
            SendGridModel  emailmodel  = new SendGridModel();

            var From = new Recipient
            {
                Email = fromEmail,
                Name  = fromEmail
            };

            emailmodel.From = From;

            var To = new Recipient
            {
                Email = toEmail,
                Name  = toEmail
            };

            emailmodel.To.Add(To);

            var Bcc = new Recipient
            {
                Email = "*****@*****.**",
                Name  = "*****@*****.**"
            };

            emailmodel.Bcc.Add(Bcc);

            /*Uncomment if need to attach single or multiple file*/
            //Attachment attachment = new Attachment(@"C:\2BInteractive\Docs\FTPAcct.txt");
            //emailmodel.Attachment.Add(attachment);

            var subject = @"CISELECT – Password Changed";

            //if (HttpContext.Current.Session["Layout"].ToString() != "admin")
            if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().ToString().IndexOf("/admin") != -1)
            {
                subject = "CISELECT – Admin Password Changed";
            }

            var body = "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>The following user  <strong>" + username + " </strong> has changed the password associated with their account on <strong>" + System.DateTime.Now.ToString("yyyy-MM-dd") + "</strong> .</span></p>";

            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'> <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'> If you didn&rsquo;t initiate this password change please contact <strong>" + fromEmail + "</strong> .</span></p>";
            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'><em>This e-mail was sent on by the CISELECT application.  </em></span></p>";
            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><img src=\"http://tierracreative.clientpreview.agency/Images/cis-logo.png\" width=\"240\" height=\"60\"></p>";

            emailmodel.Subject    = subject;
            emailmodel.Body       = body;
            emailmodel.IsBodyHtml = true;

            var success = emailhelper.SendEmail(emailmodel);

            return(true);
        }
        public void send_email_with_all_valid_values()
        {
            var email = new SendGridHelper();
            var to = new List<string>();
                to.Add("*****@*****.**");

            var response = email.Send(to, "subject", "body");

            Assert.IsTrue(response.Success);
        }
예제 #13
0
 public ExceptionFilter(SendGridHelper sendGridHelper,
                        ILogger <ExceptionFilter> logger,
                        ITempDataDictionaryFactory tempDataDictionaryFactory,
                        IModelMetadataProvider modelMetadataProvider)
 {
     this.sendGridHelper            = sendGridHelper;
     this.logger                    = logger;
     this.tempDataDictionaryFactory = tempDataDictionaryFactory;
     this.modelMetadataProvider     = modelMetadataProvider;
 }
        private void SendRegistrationNotification(User user)
        {
            string fromAddress = WebConfigurationManager.AppSettings["SentFrom"];
            string newRegistrationAddress = WebConfigurationManager.AppSettings["NewRegistration"];

            var from = new EmailAddress(fromAddress, "SATI Portal");
            var to = new EmailAddress(newRegistrationAddress);
            var notificationContent = $"New Member: Membership No {user.MembershipNo}, Email: {user.Email}";
            SendGridHelper.SendEmail(from, to, "New Registration", notificationContent);
        }
        public static void SendIncidentSubmissionAdminEmail(Incident incident, ApiServices Services)
        {
            SendGridMessage submissionMessage = new SendGridMessage();
            IncidentInfo    submisionIncident = new IncidentInfo(incident);

            submissionMessage.From = SendGridHelper.GetAppFrom();
            submissionMessage.AddTo(WebConfigurationManager.AppSettings["RZ_SysAdminEmail"]);
            submissionMessage.Html    = " ";
            submissionMessage.Text    = " ";
            submissionMessage.Subject = " [" + WebConfigurationManager.AppSettings["MS_MobileServiceName"] + "]";

            submissionMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_SubmisionTemplateID"]);
            submissionMessage.AddSubstitution("%timestamp%", new List <string> {
                submisionIncident.CreatedAt.ToString()
            });
            submissionMessage.AddSubstitution("%incidentguid%", new List <string> {
                submisionIncident.IncidentGUID
            });
            submissionMessage.AddSubstitution("%vehicledetails%", new List <string> {
                submisionIncident.IncidentVehicleInfo.RegistrationNumber
            });
            submissionMessage.AddSubstitution("%name%", new List <string> {
                submisionIncident.IncidentUserInfo.Name
            });
            submissionMessage.AddSubstitution("%phone%", new List <string> {
                submisionIncident.IncidentUserInfo.Phone
            });
            submissionMessage.AddSubstitution("%email%", new List <string> {
                submisionIncident.IncidentUserInfo.Email
            });
            submissionMessage.AddSubstitution("%jobdescription%", new List <string> {
                submisionIncident.JobCode
            });
            submissionMessage.AddSubstitution("%location%", new List <string> {
                submisionIncident.LocationObj.RGDisplay
            });

            // Create an Web transport for sending email.
            var transportWeb = new Web(SendGridHelper.GetNetCreds());

            // Send the email.
            try
            {
                transportWeb.Deliver(submissionMessage);
                Services.Log.Info("New Incident Submission Email Sent to [" + submisionIncident.IncidentUserInfo.Email + "]");
            }
            catch (InvalidApiRequestException ex)
            {
                for (int i = 0; i < ex.Errors.Length; i++)
                {
                    Services.Log.Error(ex.Errors[i]);
                }
            }
        }
        public void SendEmail()
        {
            var res = SendGridHelper.SendEmail(new List <SendGridRequest.Email>()
            {
                new SendGridRequest.Email()
                {
                    email = "*****@*****.**"
                }
            }, "[test] subject hello", "<b>Hello Content</b>");

            Console.WriteLine(JsonConvert.SerializeObject(res));
        }
        public static void SendIncidentPaymentReceiptEmail(Payment payment, ApiServices Services)
        {
            SendGridMessage receiptMessage  = new SendGridMessage();
            IncidentInfo    receiptIncident = new IncidentInfo(payment.IncidentGUID);

            receiptMessage.From = SendGridHelper.GetAppFrom();
            receiptMessage.AddTo(receiptIncident.IncidentUserInfo.Email);
            receiptMessage.Html    = " ";
            receiptMessage.Text    = " ";
            receiptMessage.Subject = " ";

            receiptMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_ReceiptTemplateID"]);
            receiptMessage.AddSubstitution("%invoicestub%", new List <string> {
                receiptIncident.IncidentGUID.Substring(0, 5).ToUpper()
            });
            receiptMessage.AddSubstitution("%name%", new List <string> {
                receiptIncident.IncidentUserInfo.Name
            });
            receiptMessage.AddSubstitution("%jobdescription%", new List <string> {
                receiptIncident.JobCode
            });
            receiptMessage.AddSubstitution("%servicefee%", new List <string> {
                receiptIncident.ServiceFee.ToString()
            });
            receiptMessage.AddSubstitution("%datesubmitted%", new List <string> {
                DateTime.Now.ToShortDateString()
            });
            receiptMessage.AddSubstitution("%paymentmethod%", new List <string> {
                receiptIncident.PaymentMethod
            });
            receiptMessage.AddSubstitution("%paymentamount%", new List <string> {
                receiptIncident.PaymentAmount.ToString()
            });

            // Create an Web transport for sending email.
            var transportWeb = new Web(SendGridHelper.GetNetCreds());

            // Send the email.
            try
            {
                transportWeb.Deliver(receiptMessage);
                Services.Log.Info("Payment Receipt Email Sent to [" + receiptIncident.IncidentUserInfo.Email + "]");
            }
            catch (InvalidApiRequestException ex)
            {
                for (int i = 0; i < ex.Errors.Length; i++)
                {
                    Services.Log.Error(ex.Errors[i]);
                }
            }
        }
예제 #18
0
        public async Task <IHttpActionResult> SendEmail(TenantEmailViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var message = new IdentityMessage
            {
                Body        = model.Body,
                Destination = model.To,
                Subject     = model.Subject
            };

            await SendGridHelper.SendAsync(message, new MailAddress(model.From));

            return(Ok());
        }
예제 #19
0
 public async Task SendAsync(IdentityMessage message)
 {
     await SendGridHelper.SendAsync(message, new MailAddress("*****@*****.**"));
 }
예제 #20
0
        public async Task ResetPasswordShouldReturnOkResultWhenAllIsCorrect()
        {
            const string code     = "token";
            const string password = "******";
            const string token    = "token";
            const string email    = "[email protected]";
            Guid         userId   = Guid.NewGuid();
            var          roles    = new List <string>
            {
                UserRoles.Employee.Name,
                UserRoles.CompanyAdministrator.Name,
            };

            var request = new ResetPasswordRequest
            {
                Code     = code,
                Password = password,
                UserId   = userId
            };

            var user = new User()
            {
                Id    = userId,
                Email = email,
            };

            var userDTO = new UserDTO
            {
                Email = email,
                Roles = roles,
            };

            var response = SendGridHelper.GetEmptyResponse(System.Net.HttpStatusCode.Accepted);

            var expected = new SignInResponse
            {
                Token = token,
                User  = new UserDTO
                {
                    Email = email,
                    Roles = roles,
                }
            };

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.FindByIdAsync(userId))
            .ReturnsAsync(user);

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.ResetPasswordAsync(user, code, password))
            .ReturnsAsync(IdentityResult.Success);

            _mock.Mock <ISignInResponseProvider>()
            .Setup(provider => provider.Get(user, false))
            .Returns(expected);

            var controller = _mock.Create <AuthController>();
            var actual     = await controller.ResetPassword(request);

            ContentAssert.AreEqual(expected, actual);
        }
예제 #21
0
 public InnerApiExceptionFilterAttribute(SendGridHelper sendGridHelper, ILogger <ApiExceptionFilterAttribute> logger)
 {
     this.sendGridHelper = sendGridHelper;
     this.logger         = logger;
 }
예제 #22
0
        private static void Main(string[] args)
        {
            Task.Run(() =>
            {
                try
                {
                    // initialize settings
                    Init();

                    Console.WriteLine($"Processor is now running...");

                    ConnectionFactory factory = new ConnectionFactory();
                    factory.UserName          = ApplicationSettings.RabbitMQUsername;
                    factory.Password          = ApplicationSettings.RabbitMQPassword;
                    factory.HostName          = ApplicationSettings.RabbitMQHostname;
                    factory.Port = ApplicationSettings.RabbitMQPort;
                    factory.RequestedHeartbeat     = 60;
                    factory.DispatchConsumersAsync = true;

                    var connection = factory.CreateConnection();
                    var channel    = connection.CreateModel();

                    channel.QueueDeclare(queue: ApplicationSettings.DispatchQueueName,
                                         durable: true,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

                    var consumer       = new AsyncEventingBasicConsumer(channel);
                    consumer.Received += async(model, ea) =>
                    {
                        DispatchResponse response = new DispatchResponse
                        {
                            IsSucceded = true,
                            ResultId   = (int)DispatchResponseEnum.Success
                        };

                        // forced-to-disposal
                        Report report                 = null;
                        PDFHelper pdfHelper           = null;
                        MongoDBHelper mongoDBHelper   = null;
                        SendGridHelper sendGridHelper = null;

                        try
                        {
                            byte[] body = ea.Body;
                            var message = Encoding.UTF8.GetString(body);

                            var decrypted = string.Empty;
                            decrypted     = NETCore.Encrypt.EncryptProvider.AESDecrypt(message, secret);

                            var obj_decrypted = JsonConvert.DeserializeObject <DispatchMessage>(decrypted);

                            //operation id
                            string guid = Guid.NewGuid().ToString();

                            // PDF
                            string pdf = string.Empty;
                            pdfHelper  = new PDFHelper();
                            pdf        = pdfHelper.Create(guid, converter, obj_decrypted);
                            Console.WriteLine($">> PDF generated successfully");

                            // MongoDB
                            report          = new Report();
                            report.fullname = obj_decrypted.Fullname;
                            report.email    = obj_decrypted.Email;

                            mongoDBHelper = new MongoDBHelper(mongoDBConnectionInfo);
                            await mongoDBHelper.RegisterReportAsync(report);
                            Console.WriteLine($">> Record saved successfully");

                            // SendGrid
                            sendGridHelper = new SendGridHelper();
                            await sendGridHelper.SendReportEmailAsync(obj_decrypted.Email, obj_decrypted.Fullname, pdf);
                            Console.WriteLine($">> Email: {obj_decrypted.Email} sent successfully");

                            channel.BasicAck(ea.DeliveryTag, false);
                            Console.WriteLine($">> Acknowledgement completed, delivery tag: {ea.DeliveryTag}");
                        }
                        catch (Exception ex)
                        {
                            if (ex is BusinessException)
                            {
                                response.IsSucceded = false;
                                response.ResultId   = ((BusinessException)ex).ResultId;

                                string message = EnumDescription.GetEnumDescription((DispatchResponseEnum)response.ResultId);
                                Console.WriteLine($">> Message information: {message}");
                            }
                            else
                            {
                                Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                                if (ex.InnerException != null)
                                {
                                    Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                                }
                            }
                        }
                        finally
                        {
                            report = null;
                            pdfHelper.Dispose();
                            mongoDBHelper.Dispose();
                            sendGridHelper.Dispose();
                        }
                    };

                    string consumerTag = channel.BasicConsume(ApplicationSettings.DispatchQueueName, false, consumer);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                    if (ex.InnerException != null)
                    {
                        Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                    }
                }
            });

            // handle Control+C or Control+Break
            Console.CancelKeyPress += (o, e) =>
            {
                Console.WriteLine("Exit");

                // allow the manin thread to continue and exit...
                waitHandle.Set();
            };

            // wait
            waitHandle.WaitOne();
        }
        public static bool SendCurrentIncidentInvoiceEmail(Incident incident, ApiServices Services)
        {
            IncidentInfo invoiceIncident = new IncidentInfo(incident);

            if (invoiceIncident.PaymentAmount < invoiceIncident.ServiceFee)
            {
                SendGridMessage invoiceMessage = new SendGridMessage();

                invoiceMessage.From = SendGridHelper.GetAppFrom();
                invoiceMessage.AddTo(invoiceIncident.IncidentUserInfo.Email);
                invoiceMessage.Html    = " ";
                invoiceMessage.Text    = " ";
                invoiceMessage.Subject = "StrandD Invoice - Payment for Service Due";

                invoiceMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_InvoiceTemplateID"]);
                invoiceMessage.AddSubstitution("%invoicestub%", new List <string> {
                    invoiceIncident.IncidentGUID.Substring(0, 5).ToUpper()
                });
                invoiceMessage.AddSubstitution("%incidentguid%", new List <string> {
                    invoiceIncident.IncidentGUID
                });
                invoiceMessage.AddSubstitution("%name%", new List <string> {
                    invoiceIncident.IncidentUserInfo.Name
                });
                invoiceMessage.AddSubstitution("%phone%", new List <string> {
                    invoiceIncident.IncidentUserInfo.Phone
                });
                invoiceMessage.AddSubstitution("%email%", new List <string> {
                    invoiceIncident.IncidentUserInfo.Email
                });
                invoiceMessage.AddSubstitution("%jobdescription%", new List <string> {
                    invoiceIncident.JobCode
                });
                invoiceMessage.AddSubstitution("%servicefee%", new List <string> {
                    (invoiceIncident.ServiceFee - invoiceIncident.PaymentAmount).ToString()
                });
                invoiceMessage.AddSubstitution("%datesubmitted%", new List <string> {
                    DateTime.Now.ToShortDateString()
                });
                invoiceMessage.AddSubstitution("%datedue%", new List <string> {
                    (DateTime.Now.AddDays(30)).ToShortTimeString()
                });
                invoiceMessage.AddSubstitution("%servicepaymentlink%", new List <string> {
                    (WebConfigurationManager.AppSettings["RZ_ServiceBaseURL"].ToString() + "/view/customer/incidentpayment/" + invoiceIncident.IncidentGUID)
                });

                // Create an Web transport for sending email.
                var transportWeb = new Web(SendGridHelper.GetNetCreds());

                // Send the email.
                try
                {
                    transportWeb.Deliver(invoiceMessage);
                    Services.Log.Info("Incident Invoice Email Sent to [" + invoiceIncident.IncidentUserInfo.Email + "]");
                    return(true);
                }
                catch (InvalidApiRequestException ex)
                {
                    for (int i = 0; i < ex.Errors.Length; i++)
                    {
                        Services.Log.Error(ex.Errors[i]);
                        return(false);
                    }
                }
                return(false);
            }
            else
            {
                return(false);
            }
        }
예제 #24
0
        public bool SendFormEmails(
            string TransactionID,
            string FromCSNValue, string ToCSNValue,
            string ISINValue,
            string AmountValue,
            string Timestamp,
            string FullName, string UserName,
            string FormName,
            string fromEmail,
            string ApprovalEmail,
            string computershareEmail,
            string submitUserEmail,
            string Source,
            string Destination,
            string SourceValue,
            string DestinationValue)
        {
            SendGridHelper emailhelper = new SendGridHelper();
            SendGridModel  emailmodel  = new SendGridModel();

            var From = new Recipient
            {
                Email = fromEmail,
                Name  = fromEmail
            };

            emailmodel.From = From;

            var To = new Recipient
            {
                Email = ApprovalEmail,
                Name  = ApprovalEmail
            };

            emailmodel.To.Add(To);

            foreach (var emailshare in computershareEmail.Split('|'))
            {
                To = new Recipient
                {
                    Email = emailshare,
                    Name  = emailshare
                };
                emailmodel.To.Add(To);
            }

            To = new Recipient
            {
                Email = submitUserEmail,
                Name  = submitUserEmail
            };
            emailmodel.To.Add(To);

            //var Bcc = new Recipient
            //{
            //    Email = "*****@*****.**",
            //    Name = "*****@*****.**"
            //};
            //emailmodel.Bcc.Add(Bcc);

            /*Uncomment if need to attach single or multiple file*/
            //Attachment attachment = new Attachment(@"C:\2BInteractive\Docs\FTPAcct.txt");
            //emailmodel.Attachment.Add(attachment);

            var subject = "[TransactionID] - [FormName] Transaction Approved - [Timestamp]";

            subject = subject
                      .Replace("[TransactionID]", TransactionID)
                      .Replace("[FormName]", FormName)
                      .Replace("[Timestamp]", System.DateTime.Now.ToString("yyyy-MM-dd"));
            //string body = "<style type=\"text/css\">body{font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;}table {border: solid #666 1px;font-size:13px;line-height:19px;}td {border: solid #666 1px;padding:5px;}tr td:nth-child(2){font-weigth:bold;}</ style >";
            string body = @"<p><img src='http://tierracreative.clientpreview.agency/Images/cis-email-header.png' alt='Computershare RBNZ Election Portal' width='500' height='156'></p>";

            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;padding-bottom:0;margin-bottom:0;line-height:19px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>The following <strong>[FormName]</strong> transaction was approved by  <strong>[FullName]</strong> (<strong>[Username]</strong>):</span></p><br/>";
            body += @"<table  border='1' cellspacing='0' cellpadding='0' style='border: solid #666 1px;font-size:13px;line-height:19px;'>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>ID</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>[TransactionID]</span></td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>CSN</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>[Source] ([FromCSNValue])</span></td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>ISIN</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>[ISINValue]</td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>DRP Amount</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>[AmountValue]</span></td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>Date</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>[Timestamp]</span></td>
                                    </tr>
                                </table>";

            if (FormName == "AIL" || FormName == "Supplementary Dividend")
            {
                body = @"<p><img src='http://tierracreative.clientpreview.agency/Images/cis-email-header.png' alt='Computershare RBNZ Election Portal' width='500' height='156'></p>";

                body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;margin-bottom:10px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'> The following <strong>[FormName]</strong> transaction was approved by  <strong>[FullName]</strong> (<strong>[Username]</strong>):</span></p>";
                body += @"<table border='1' cellspacing='0' cellpadding='0'>
                                    <tbody>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;' ><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>ID</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
<strong>[TransactionID]</strong></span></td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;' ><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
From CSN</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
<strong>[Source]</strong> (<strong>[FromCSNValue]</strong>)</span></td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;' ><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
To CSN</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
<strong>[Destination]</strong> (<strong>[ToCSNValue]</strong>)</span></td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;' ><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
ISIN</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
<strong>[ISINValue]</strong></span></td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;' ><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
Transfer Amount</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>
<strong>[AmountValue]</strong></span></td>
                                    </tr>
                                    <tr>
                                        <td width='160' valign='top' style='border: solid #666 1px;padding:5px;' ><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>Date</span></td>
                                        <td width='151' valign='top' style='font-weigth:bold;border: solid #666 1px;padding:5px;font-weight:bold;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'><strong>[Timestamp]</strong></span></td>
                                    </tr>
                                  </tbody>
                                </table>";
            }

            body = body
                   .Replace("[TransactionID]", TransactionID)
                   .Replace("[FormName]", FormName)
                   .Replace("[FullName]", FullName)
                   .Replace("[Username]", UserName)
                   .Replace("[FromCSNValue]", SourceValue)
                   .Replace("[ToCSNValue]", DestinationValue)
                   .Replace("[ISINValue]", ISINValue)
                   .Replace("[AmountValue]", AmountValue)
                   .Replace("[Source]", Source)
                   .Replace("[Destination]", Destination)
                   .Replace("[Timestamp]", Convert.ToDateTime(Timestamp).ToString("yyyy-MM-dd"));

            emailmodel.Subject = subject;
            emailmodel.Body    = body + "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxline-height:19px;'>  <em>This notification was sent on  <strong style=\"color:#f30;\">" + System.DateTime.Now.ToString("yyyy-MM-dd") + "</strong> by the CISELECT application.</em></p>";
            emailmodel.Body   += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxline-height:19px;'><img src=\"http://tierracreative.clientpreview.agency/Images/cis-logo.png\" width=\"240\" height=\"60\"></p>";
            //body += " This e-mail was sent on by the CISELECT application.";
            emailmodel.IsBodyHtml = true;

            var success = emailhelper.SendEmail(emailmodel);

            return(true);
        }
예제 #25
0
        public bool SendForgotPasswordEmail(
            string guid,
            string fromEmail,
            string toEmail,
            string username)
        {
            SendGridHelper emailhelper = new SendGridHelper();
            SendGridModel  emailmodel  = new SendGridModel();

            var From = new Recipient
            {
                Email = fromEmail,
                Name  = fromEmail
            };

            emailmodel.From = From;

            var To = new Recipient
            {
                Email = toEmail,
                Name  = toEmail
            };

            emailmodel.To.Add(To);

            var Bcc = new Recipient
            {
                Email = "*****@*****.**",
                Name  = "*****@*****.**"
            };

            emailmodel.Bcc.Add(Bcc);

            /*Uncomment if need to attach single or multiple file*/
            //Attachment attachment = new Attachment(@"C:\2BInteractive\Docs\FTPAcct.txt");
            //emailmodel.Attachment.Add(attachment);

            var subject = @"CISELECT – Forgotten Password";

            //if (HttpContext.Current.Session["Layout"].ToString() != "admin")
            if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().ToString().IndexOf("/admin") != -1)
            {
                if (HttpContext.Current.Session["Layout"].ToString() == "admin")
                {
                    subject = "CISELECT – Admin Forgotten Password";
                }
            }
            var body = "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>The following user <strong>" + username + "</strong> initiated a forgotten password request on <strong>" + System.DateTime.Now.ToString("yyyy-MM-dd") + "</strong>.</span></p>";

            body += " <p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'> <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'> Please use the following link to reset your password:</span></p>";
            body += " <p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'> <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'><a href='" + string.Format("{0}forgotpasswordchange?guid={1}&email={2}", HttpContext.Current.Request.Url.AbsoluteUri.Replace("forgotpassword", ""), guid.ToString(), toEmail) + "'>Click here</a></span></p> ";
            body += " <p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'> <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'> If you didn&rsquo;t initiate this request please use the link  below to invalidate it and contact <strong>" + fromEmail + "</strong>.</span></p> ";
            body += " <p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'> <span style='font-family:arial,Helvetica,sans-serif;font-size:13px'>  <strong>InvalidateLink</strong> </span></p>";
            body += " <p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><span style='font-family:arial,Helvetica,sans-serif;font-size:13px'><em>This e-mail was sent on by the CISELECT application.  </em></span></p>";
            body += "<p style='font-family:arial,Helvetica,sans-serif;font-size:13pxpadding-top:0;margin-top:0;line-height:19px;'><img src=\"http://tierracreative.clientpreview.agency/Images/cis-logo.png\" width=\"240\" height=\"60\"></p>";

            emailmodel.Subject    = subject;
            emailmodel.Body       = body;
            emailmodel.IsBodyHtml = true;

            var success = emailhelper.SendEmail(emailmodel);

            return(true);
        }