예제 #1
0
        public async Task <HttpResponseMessage> GetByEmailAsync(string email)
        {
            try
            {
                ItemResponse <EmailViewModel> resp = new ItemResponse <EmailViewModel>();
                resp.Item = _userService.GetByEmail(email);
                var Id = resp.Item.Id;

                if (resp.Item.isConfirmed == false)
                {
                    var AuthTokenID       = _userService.AuthorizationToken(Id);
                    var ConfirmationToken = AuthTokenID.ConfirmationToken;
                    var SendEmail         = _userService.GetEmail(ConfirmationToken, email);
                    int authTokenId       = _userService.CreateAuthToken(AuthTokenID);

                    var response = await SendGridEmail.SendEmail(SendEmail);

                    return(Request.CreateResponse(HttpStatusCode.OK, resp));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, resp));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ex));
            }
        }
예제 #2
0
        public async Task TestNuGetEmail()
        {
            // Create debug log and fake SendGrid key
            var debugLog        = new Log(LogDestination.Debug, Log.DefaultCategoryName);
            var fakeSendGridKey = TestUtilities.CreateUniqueDigits();

            // Initalize email class
            var emailSender = new SendGridEmail(debugLog, fakeSendGridKey);

            // Create an email message with a To: field set to null
            IEmail emailMsg = new Email()
            {
                To = null
            };

            // Check that this raises the correct exception. Since EMail raises a generic exception,
            // we catch the exception here and test that it includes the expected error message
            try
            {
                await emailSender.SendEmail(emailMsg);
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.Message.Contains("got empty email address list"));
                return;
            }

            // Code should never each here
            Assert.IsTrue(false);
        }
예제 #3
0
        public async System.Threading.Tasks.Task <ActionResult> Contact(EmailModel e)
        {
            if (ModelState.IsValid)
            {
                await SendGridEmail.SendEmailWithGrid(e);

                ViewBag.sent = "Your email has been sent!";
                return(View());
            }
            return(View(e));
        }
예제 #4
0
        public ActionResult RcoverPwd(string txtUserName)
        {
            var user = _userRepo.GetUserByName(txtUserName);

            if (user != null)
            {
                string url  = "http://localhost:62710/User/ChangePassword/" + user.Id;
                string body = "<p>You have requested for reset password.</p><p>Click here to <a href='" + url + "'>Change Password</a></p>";  // link for small page
                SendGridEmail.SendEmail(user.Email, "Change Password", body);
                return(RedirectToAction("SuccessMessage", "User", new { }));
            }
            else
            {
                return(RedirectToAction("Login", "User", new { }));
            }
        }
예제 #5
0
        public void SimpleEmailTest()
        {
            SendGridEmail email = new SendGridEmail(
                contents: "<html><head></head><body><!-- BODY START -->Test<!-- BODY END --></body></html>",
                subject: "Test Email",
                recipients: new System.Collections.Generic.List <IEmailRecipient>()
            {
                new EmailRecipient()
                {
                    Name = "Ameen Tayyebi", EmailAddress = "*****@*****.**"
                }
            },
                fromAddress: "*****@*****.**",
                fromName: "Stockwinners.com");

            email.Send();
        }
예제 #6
0
        public Task <HttpResponseMessage> SendEmailAsync(string email, string subject, string message, string name)
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BEARER", Options.sendgridkey);

            var payload = new SendGridEmail
            {
                content = new List <EmailMessage>
                {
                    new EmailMessage("text/html", message)
                },
                personalizations = new List <Personalization>
                {
                    new Personalization
                    {
                        to      = new [] { new EmailAddress(email, name) },
                        subject = subject
                    }
                },
                from     = new EmailAddress("*****@*****.**", "SCBWI Florida Registration Bot"),
                reply_to = support_email
            };

            if (EmailOpts.ccra || EmailOpts.sendtoself)
            {
                payload.personalizations.First().bcc = new List <EmailAddress>();
            }

            if (EmailOpts.ccra)
            {
                payload.personalizations.First().bcc.Add(support_email);
            }

            if (EmailOpts.sendtoself)
            {
                payload.personalizations.First().bcc.Add(new EmailAddress(EmailOpts.self, ""));
            }

            var payloadAsJson = JsonConvert.SerializeObject(payload);

            _logger.LogInformation($"Sending email: {payloadAsJson}");

            return(client.PostAsJsonAsync("https://api.sendgrid.com/v3/mail/send", payload));
        }
예제 #7
0
 public SendGridMessage(SendGridEmail to, string subject, SendGridEmail from, string message, IEnumerable <SendGridEmail> bcc = null, string type = TypeHtml)
 {
     this.Personalizations = new List <SendGridPersonalization>
     {
         new SendGridPersonalization
         {
             To = new List <SendGridEmail> {
                 to
             },
             Bcc     = bcc,
             Subject = subject
         }
     };
     this.From    = from;
     this.Content = new List <SendGridContent> {
         new SendGridContent(type, message)
     };
 }
예제 #8
0
        public async Task <HttpResponseMessage> Post(RegistrationAddRequest model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var    webClient         = new WebClient();
                    string verification      = webClient.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", _configService.ConvertConfigValue_String("Google_Recaptcha"), model.recaptchaResponse));
                    var    recaptchaResponse = (JObject.Parse(verification)["success"].Value <bool>());

                    if (recaptchaResponse == true)
                    {
                        int id    = _userService.Create(model);
                        var email = model.Email;

                        var AuthTokenID       = _userService.AuthorizationToken(id);
                        var ConfirmationToken = AuthTokenID.ConfirmationToken;
                        var SendEmail         = _userService.GetEmail(ConfirmationToken, email);
                        int authTokenId       = _userService.CreateAuthToken(AuthTokenID);

                        ItemResponse <int> resp = new ItemResponse <int>();
                        var response            = await SendGridEmail.SendEmail(SendEmail);

                        return(Request.CreateResponse(HttpStatusCode.OK, resp));
                    }
                    else
                    {
                        ErrorResponse resp = new ErrorResponse("Uncessful Registration Attempt");
                        return(Request.CreateResponse(HttpStatusCode.OK, resp));
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
예제 #9
0
        /// <summary>
        /// Method to format test result messages and send them in an email
        /// Note that this is done only for failed tests
        /// </summary>
        /// <param name="runId">run id</param>
        /// <param name="hasTestFailed">flag to check of any test has failed</param>
        /// <param name="testResultMessages">test result messages for failed tests</param>
        private static void FormatResultAndSendEmail(int runId, bool hasTestFailed, IEnumerable <string> testResultMessages)
        {
            // If any tests failed during this run, check whether we should send e-mail about them
            if (hasTestFailed && sendEmailOnTestFailure)
            {
                Email msg = new Email();
                try
                {
                    msg.Subject = string.Format("Failed tests during run#:{0} out of {1}", runId, numberOfRuns);
                    msg.To      = new List <string>()
                    {
                        TestConstants.FailedTestsEmail
                    };
                    msg.Category = "EndToEnd Testing";
                    msg.HtmlBody = string.Join("<br><br>", testResultMessages);
                    string        configFilePath = ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + TestConstants.ConfigFileName;
                    string        sendGridKey    = TestUtilities.GetSendGridKey(configFilePath);
                    var           log            = new Log(LogDestination.Console, Log.DefaultCategoryName);
                    SendGridEmail sendingClient  = new SendGridEmail(log, sendGridKey);
                    sendingClient.SendEmail(msg).Wait();
                }
                catch (Exception e)
                {
                    // SendEmail failed. Report the error on the console and move on.
                    System.ConsoleColor oldColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Encountered an error during SendEmail:");
                    Console.WriteLine(e.Message);
                    if (e.InnerException != null)
                    {
                        Console.WriteLine(e.InnerException.Message);
                    }

                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine();
                    Console.WriteLine("Tried to send the following message:");
                    Console.WriteLine(msg.Subject);
                    Console.WriteLine(msg.HtmlBody);
                    Console.ForegroundColor = oldColor;
                }
            }
        }
        public async Task <IActionResult> SendQuestionForm([FromBody] QuestionFormData questionForm)
        {
            // Get seller emails list
            var storeRepository = uow.GetRepository <StoreRepository>();
            var adminLojaEmails = await storeRepository.GetAdminsEmailFromStore(questionForm.StoreId);

            // Send an email for each person in store
            var emailService = new SendGridEmail("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");

            // Read email template
            var emailTemplate = string.Empty;

            using (var reader = new StreamReader(Path.Combine(environment.ContentRootPath, "EmailTemplates", "client_without_agent.html")))
            {
                emailTemplate = await reader.ReadToEndAsync();
            }

            // Send emails
            var tempEmailTemplate = string.Empty;

            foreach (var email in adminLojaEmails)
            {
                tempEmailTemplate = emailTemplate
                                    .Replace("{{name}}", questionForm.Name)
                                    .Replace("{{contact}}", questionForm.Phone)
                                    .Replace("{{message}}", questionForm.Message);

                await emailService.EnviarEmail(
                    to : email.Email,
                    header : tempEmailTemplate,
                    subject : "Cliente sem atendimento!",
                    fromAddress : "*****@*****.**",
                    name : "Chat Moveleiros",
                    textPlain : $"O cliente {questionForm.Name} não foi atendido. " +
                    $"O contato informado é {questionForm.Phone}. " +
                    $"A mensagem deixada foi {questionForm.Message}"
                    );
            }

            return(Ok());
        }
예제 #11
0
        /// <summary>
        /// Maps the email model to send grid specific request model
        /// </summary>
        /// <param name="email">email model</param>
        /// <returns>SendGridEmail</returns>
        public SendGridEmail mapToSendGridEmail(EmailModel email)
        {
            //create the send grid specific model
            var sendGridEmail = new SendGridEmail()
            {
                subject          = email.Subject,
                personalizations = new List <Personalization>(),
                content          = new List <Content>()
            };

            var personalization = new Personalization()
            {
                to = new List <Recipient>(),
                //cc = new List<Recipient>(),
                //bcc = new List<Recipient>()
            };


            personalization.to.AddRange(email.To.Select(t => new Recipient {
                email = t
            }));
            //personalization.cc.AddRange(email.Cc.Select(t => new Recipient { email = t }));
            //personalization.bcc.AddRange(email.Bcc.Select(t => new Recipient { email = t }));

            sendGridEmail.personalizations.Add(personalization);

            var content = new Content()
            {
                type = "text/plain", value = email.Message
            };

            sendGridEmail.content.Add(content);

            //TODO: From address is hard coded. Place to config
            sendGridEmail.from = new From()
            {
                email = "*****@*****.**"
            };

            return(sendGridEmail);
        }
예제 #12
0
        public void SendOneEmail()
        {
            var    log            = new Log(LogDestination.Debug, Log.DefaultCategoryName);
            string configFilePath = ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + TestConstants.ConfigFileName;
            string sendGridKey    = TestUtilities.GetSendGridKey(configFilePath);

            // setup the email to send
            Email email = new Email();

            email.To = new List <string>();
            email.To.Add(TestConstants.FailedTestsEmail);
            email.Subject  = "testing SendGrid";
            email.HtmlBody = "<html><H1>not much here</H1></html>";
            email.TextBody = "not much here";
            email.Category = "UnitTest";

            // send the email
            SendGridEmail emailSender = new SendGridEmail(log, sendGridKey);

            emailSender.SendEmail(email).Wait();
        }
예제 #13
0
        public void Insert(User user)
        {
            // Create random hash value for for DB
            string randHash = Randomize();

            string        DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
            SqlConnection myConn    = new SqlConnection(DBConnect);

            string     sqlStmtInsert = "INSERT INTO [User] (name, password, email, hash) VALUES (@paraName, @paraPassword, @paraEmail, @paraHash)";
            SqlCommand sqlCmd        = new SqlCommand(sqlStmtInsert, myConn);

            sqlCmd.Parameters.AddWithValue("@paraName", user.name);
            sqlCmd.Parameters.AddWithValue("@paraEmail", user.email);
            sqlCmd.Parameters.AddWithValue("@paraHash", randHash);

            // Send Email Verification
            SendGridEmail email    = new SendGridEmail();
            string        hrefLink = "http://*****:*****@paraPassword", hashedPw);

            myConn.Open();

            int k = sqlCmd.ExecuteNonQuery();

            if (k != 0)
            {
                System.Diagnostics.Debug.WriteLine("User inserted into database");
            }

            myConn.Close();
        }
예제 #14
0
 public void SendEmail(string to, string subject, string body)
 {
     SendGridEmail.SendEmail(to, subject, body);
 }
예제 #15
0
        /// <summary>
        /// Runs tests one-by-one in a loop
        /// </summary>
        /// <param name="args">Argument list</param>
        private static void Main(string[] args)
        {
            ParseArgs(args);

            bool  hasTestFailed = false;
            Email msg           = new Email();

            foreach (var v in TestClasses)
            {
                var kvFactory = new KVFactory();
                foreach (IKV kv in kvFactory.CreateKV())
                {
                    // Make a test class object
                    var      currentAssembly   = Assembly.GetExecutingAssembly();
                    var      currentNamespace  = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
                    object[] constructorParams = new object[1] {
                        kv
                    };
                    object classInstance = ReflectionUtils.CreateClassInstance(currentAssembly, currentNamespace, v, constructorParams);

                    if (classInstance == null)
                    {
                        Console.WriteLine("Error: couldn't find the class with the parameter types specified!!!");
                        throw new Exception("Could not find test class with the parameter types specified in code!");
                    }

                    // For each method of the class labelled with TestMethod attribute
                    foreach (var testMethod in ReflectionUtils.GetMethodsWithTypeTAttribute(classInstance.GetType(), typeof(TestMethodAttribute)))
                    {
                        DateTime testStartTime = DateTime.Now;

                        Console.WriteLine(testMethod.Name + " started against " + TestUtilities.PrettyServerName(TestConstants.ServerApiBaseUrl));
                        try
                        {
                            Task test = (Task)testMethod.Invoke(classInstance, null);

                            // Check whether the test terminates on time
                            if (test.Wait(secsPerTest * 1000))
                            {
                                Console.WriteLine(testMethod.Name + " finished within {0} secs.", DateTime.Now.Subtract(testStartTime).Seconds);
                            }
                            else
                            {
                                Console.WriteLine(testMethod.Name + " has not finished within {0} secs. Moved on.", secsPerTest);
                                throw new Exception(string.Format(testMethod.Name + " has not finished within {0} secs. Moved on.", secsPerTest));
                            }
                        }
                        catch (Exception ex)
                        {
                            // Write the error to the console
                            Console.WriteLine(ex.ToString());

                            // If this test is the first failed test in this run, create a new email, otherwise just appent to the message
                            if (!hasTestFailed)
                            {
                                msg.Subject = "Failed unit tests";
                                msg.To      = new List <string>()
                                {
                                    TestConstants.FailedTestsEmail
                                };
                                msg.Category = "Unit Testing";
                                msg.HtmlBody = TestUtilities.Exception2HtmlEmail(testMethod.Name, ex);
                            }
                            else
                            {
                                msg.HtmlBody += "<br><br>" + TestUtilities.Exception2HtmlEmail(testMethod.Name, ex);
                            }

                            hasTestFailed = true;
                        }
                    }
                }
            }

            // If any tests failed during this run, check whether we should send e-mail about them
            if (hasTestFailed && sendEmailOnTestFailure)
            {
                string configFilePath = ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + TestConstants.ConfigFileName;
                string sendGridKey    = TestUtilities.GetSendGridKey(configFilePath);

                try
                {
                    var           log           = new Log(LogDestination.Console, Log.DefaultCategoryName);
                    SendGridEmail sendingClient = new SendGridEmail(log, sendGridKey);
                    sendingClient.SendEmail(msg).Wait();
                }
                catch (Exception e)
                {
                    // SendEmail failed. Report the error on the console and move on.
                    System.ConsoleColor oldColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Encountered an error during SendEmail:");
                    Console.WriteLine(e.Message);
                    if (e.InnerException != null)
                    {
                        Console.WriteLine(e.InnerException.Message);
                    }

                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine();
                    Console.WriteLine("Tried to send the following message:");
                    Console.WriteLine(msg.Subject);
                    Console.WriteLine(msg.HtmlBody);
                    Console.ForegroundColor = oldColor;
                }
            }
        }