Пример #1
0
        public async Task <bool> SendEmail(string emailAddress, string subject, string message)
        {
            try
            {
                var msg = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(
                    new SendGrid.Helpers.Mail.EmailAddress(VoatSettings.Instance.EmailAddress, VoatSettings.Instance.SiteName),
                    new SendGrid.Helpers.Mail.EmailAddress(emailAddress),
                    subject,
                    null,
                    message);

                var trackingSettings = new SendGrid.Helpers.Mail.TrackingSettings();
                trackingSettings.ClickTracking = new SendGrid.Helpers.Mail.ClickTracking();
                trackingSettings.OpenTracking  = new SendGrid.Helpers.Mail.OpenTracking();

                trackingSettings.ClickTracking.Enable = false;
                trackingSettings.OpenTracking.Enable  = false;

                msg.TrackingSettings = trackingSettings;

                var sendGridClient = new SendGrid.SendGridClient(_connectionString);

                var response = await sendGridClient.SendEmailAsync(msg);

                return(response.StatusCode == System.Net.HttpStatusCode.Accepted);
            }
            catch (Exception ex)
            {
                EventLogger.Log(ex, VoatSettings.Instance.Origin);
                return(false);
            }
        }
Пример #2
0
        public static async Task <bool> SendInvitationEmailAsync(string userEmailAddress, string redeemUrl)
        {
            var mailClient = new SendGrid.SendGridClient(Constants.SendGridAPIKey);

            var message = new SendGridMessage()
            {
                From       = new EmailAddress(Constants.SendGridNoReploy),
                TemplateId = Constants.SendGridTemplateId,
                Subject    = Constants.SendGridSubject,
            };

            message.AddTo(new EmailAddress(userEmailAddress));
            message.AddSubstitution("%invitationRedeemUrl%", redeemUrl);

            // Send e-mail
            var sendGridWebTransport = await mailClient.SendEmailAsync(message);

            if (sendGridWebTransport.StatusCode == HttpStatusCode.Accepted)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #3
0
        public async Task SendRegistrationEmailAsync(
            string emailTo, string emailToFullname)
        {
            //configure sendergrid api.
            string apiKey = ApplicationSettings.SendGridAPIKey;
            var    client = new SendGrid.SendGridClient(apiKey);

            //build mail.
            var    from    = new EmailAddress("*****@*****.**", "Resource Finder registration");
            var    to      = new EmailAddress($"{emailTo}", $"{emailToFullname}");
            string subject = "Resource Finder notification: Activation completed";

            var plainTextContent = string.Empty;

            var htmlContent =
                $"Hello {emailToFullname}!" +
                $"<br/><br/>" +
                $"We have successfully activate your account, you are now able to sign-in in the application." +
                $"<br/><br/>" +
                $"Thanks for using Resource Finder," +
                $"<br/>" +
                $"Resource Finder team!";

            var msg      = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);
        }
Пример #4
0
        //overload with what you want to show in the email.
        public void SendConfirmation(string email, string Name)
        {
            try
            {
                var myMessage = new SendGridMessage
                {
                    From = new EmailAddress("*****@*****.**", "Alliance")
                };


                myMessage.AddTo(email);
                string subject = "Application Status: ";
                string body    = (
                    "Dear " + Name + "<br/>" + "<br/>" +
                    "Many Thanks, " +
                    "<br/>" +
                    "Alliance Team ");

                myMessage.Subject     = subject;
                myMessage.HtmlContent = body;

                var transportWeb = new SendGrid.SendGridClient("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");

                transportWeb.SendEmailAsync(myMessage);
            }
            catch (Exception x)
            {
                Console.WriteLine(x);
            }
        }
Пример #5
0
        private SendGrid.SendGridClient Create()
        {
            var key    = _sendGridSettings.ApiKey;
            var client = new SendGrid.SendGridClient(key);

            return(client);
        }
        //Save Registration Details
        public JsonResult SaveData(SiteUser model)
        {
            model.IsValid  = false;
            model.Password = model.setPassword();

            interfaceobj.InsertModel(model);
            interfaceobj.Save();

            BuildEmailTemplate(model.SiteUserId);

            var myMessage = new SendGridMessage
            {
                From = new EmailAddress("*****@*****.**", "No-Reply")
            };

            myMessage.AddTo(model.Email);
            string subject = "Registration Received";
            string body    = ("Hi " + model.Username + " " + "\n" + "Here your booking details" + model.Password + "." +
                              "\n" + " Ensure not to share your password with anyone...  Have a great day." + "\n");

            myMessage.Subject     = subject;
            myMessage.HtmlContent = body;
            var transportWeb = new SendGrid.SendGridClient("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");

            transportWeb.SendEmailAsync(myMessage);



            TempData["SM"] = "Succesfully Registerd";

            return(Json("Registration Successfull", JsonRequestBehavior.AllowGet));
        }
Пример #7
0
        public async System.Threading.Tasks.Task <System.Net.HttpStatusCode> SendAsync()
        {
            if (System.String.IsNullOrWhiteSpace(this.APIKeyPassword))
            {
                return(System.Net.HttpStatusCode.Unauthorized);
            }

            if ((this.From == null) || (System.String.IsNullOrWhiteSpace(this.From.Address)) || (this.To == null) || (!(To.Any())) || (To.Any(i => System.String.IsNullOrWhiteSpace(i.Address))))
            {
                return(System.Net.HttpStatusCode.BadRequest);
            }

            SendGrid.SendGridClient            Client           = new SendGrid.SendGridClient(this.APIKeyPassword);
            SendGrid.Helpers.Mail.EmailAddress FromEmailAddress = new SendGrid.Helpers.Mail.EmailAddress(this.From.Address, this.From.Name);

            SendGrid.Helpers.Mail.SendGridMessage Message;
            if (this.To.Count == 1)
            {
                Message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(FromEmailAddress, new SendGrid.Helpers.Mail.EmailAddress(this.To[0].Address, this.To[0].Name), this.Subject, this.PlainTextContent, this.HTMLContent);
            }
            else
            {
                Message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmailToMultipleRecipients(FromEmailAddress, To.Select(i => new SendGrid.Helpers.Mail.EmailAddress(i.Address, i.Name)).ToList(), this.Subject, this.PlainTextContent, this.HTMLContent);
            }

            return((await Client.SendEmailAsync(Message)).StatusCode);
        }
        public async Task SendReportEmailAsync(
            string emailTo, string emailToFullname, string pdf)
        {
            //configure sendergrid api.
            string apiKey = ApplicationSettings.SendGridAPIKey;
            var    client = new SendGrid.SendGridClient(apiKey);

            //build mail.
            var    from    = new EmailAddress("*****@*****.**", "Reporting Service");
            var    to      = new EmailAddress($"{emailTo}", $"{emailToFullname}");
            string subject = "Reporting Service Notification: Report completed";

            var plainTextContent = string.Empty;

            var htmlContent =
                $"Hello {emailToFullname}!" +
                $"<br/><br/>" +
                $"We have successfully generated the requested report, please see the attachments." +
                $"<br/><br/>" +
                $"Thanks for using Reporting Service," +
                $"<br/>" +
                $"Reporting Service team";

            var msg = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

            msg.AddAttachment(new Attachment()
            {
                Type = "application/pdf", Content = pdf, Filename = "Report.pdf", ContentId = Guid.NewGuid().ToString(), Disposition = "attachment"
            });
            var response = await client.SendEmailAsync(msg);
        }
Пример #9
0
        public async Task <ActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                using (IdentityModels entities = new IdentityModels())
                {
                    var userStore = new UserStore <User>(entities);

                    var manager = new UserManager <User>(userStore);
                    manager.UserTokenProvider = new EmailTokenProvider <User>();

                    var user = new User()
                    {
                        UserName = model.EmailAddress,
                        Email    = model.EmailAddress
                    };

                    IdentityResult result = manager.Create(user, model.Password);

                    if (result.Succeeded)
                    {
                        User u = manager.FindByName(model.EmailAddress);

                        // Creates customer record in Braintree
                        string merchantId  = ConfigurationManager.AppSettings["Braintree.MerchantID"];
                        string publicKey   = ConfigurationManager.AppSettings["Braintree.PublicKey"];
                        string privateKey  = ConfigurationManager.AppSettings["Braintree.PrivateKey"];
                        string environment = ConfigurationManager.AppSettings["Braintree.Environment"];
                        Braintree.BraintreeGateway braintree = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);
                        Braintree.CustomerRequest  customer  = new Braintree.CustomerRequest();
                        customer.CustomerId = u.Id;
                        customer.Email      = u.Email;

                        var r = await braintree.Customer.CreateAsync(customer);

                        string confirmationToken = manager.GenerateEmailConfirmationToken(u.Id);

                        string sendGridApiKey = ConfigurationManager.AppSettings["SendGrid.ApiKey"];

                        SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridApiKey);
                        SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage();
                        message.Subject = string.Format("Please confirm your account");
                        message.From    = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey");
                        message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(model.EmailAddress));
                        SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/html", string.Format("<a href=\"{0}\">Confirm Account</a>", Request.Url.GetLeftPart(UriPartial.Authority) + "/MyAccount/Confirm/" + confirmationToken + "?email=" + model.EmailAddress));

                        message.AddContent(contents.Type, contents.Value);
                        SendGrid.Response response = await client.SendEmailAsync(message);

                        return(RedirectToAction("ConfirmSent"));
                    }
                    else
                    {
                        ModelState.AddModelError("EmailAddress", "Unable to register with this email address.");
                    }
                }
            }
            return(View(model));
        }
Пример #10
0
        public async System.Threading.Tasks.Task <ActionResult> Register(string username, string email, string password)
        {
            var userStore = new Microsoft.AspNet.Identity.EntityFramework.UserStore <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>();
            var manager   = new Microsoft.AspNet.Identity.UserManager <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(userStore);
            var user      = new Microsoft.AspNet.Identity.EntityFramework.IdentityUser()
            {
                UserName = username, Email = email, EmailConfirmed = false
            };

            manager.UserTokenProvider =
                new Microsoft.AspNet.Identity.EmailTokenProvider <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>();

            Microsoft.AspNet.Identity.IdentityResult result = await manager.CreateAsync(user, password);

            if (result.Succeeded)
            {
                //I have some options: log them in, or I can send them an email to "Confirm" their account details.'
                //I don't have email set up this week, so we'll come back to that.
                string confirmationToken = await manager.GenerateEmailConfirmationTokenAsync(user.Id);

                string confirmationLink = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/Confirm/" + user.Id + "?token=" + confirmationToken;

                string apiKey = System.Configuration.ConfigurationManager.AppSettings["SendGrid.ApiKey"];

                SendGrid.ISendGridClient           client = new SendGrid.SendGridClient(apiKey);
                SendGrid.Helpers.Mail.EmailAddress from   = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Coding Cookware Administrator");

                SendGrid.Helpers.Mail.EmailAddress to = new SendGrid.Helpers.Mail.EmailAddress(email);

                string subject = "Confirm your Coding Cookware Account";

                string htmlContent      = string.Format("<a href=\"{0}\">Confirm Your Account</a>", confirmationLink);
                string plainTextContent = confirmationLink;

                SendGrid.Helpers.Mail.SendGridMessage message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

                SendGrid.Response response = await client.SendEmailAsync(message);

                TempData["EmailAddress"] = email;

                return(RedirectToAction("ConfirmationSent"));


                //Commenting this out: I'm not going to log the user in on registration anymore - I'm going to send them a confirmation email instead.
                //This authentication manager will create a cookie for the current user, and that cookie will be exchanged on each request until the user logs out
                //var authenticationManager = HttpContext.GetOwinContext().Authentication;
                //var userIdentity = await manager.CreateIdentityAsync(user, Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
                //authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { }, userIdentity);
            }
            else
            {
                ViewBag.Error = result.Errors;
                return(View());
            }

            return(RedirectToAction("Index", "Home"));
        }
Пример #11
0
 /// <summary>
 /// Install-Package SendGrid
 /// </summary>
 public void SendEmailViaApi(string emailSubject, string plainTextContent, string htmlContent, string senderEmail, string senderName, string receiverEmail, string receiverName)
 {
     var client = new SendGrid.SendGridClient(this._apikey);
     var from   = new SendGrid.Helpers.Mail.EmailAddress(senderEmail, senderName);
     var to     = new SendGrid.Helpers.Mail.EmailAddress(receiverEmail, receiverName);
     //var plainTextContent = "and easy to do anywhere, even with C#";
     //var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
     var msg      = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(from, to, emailSubject, plainTextContent, htmlContent);
     var response = client.SendEmailAsync(msg).GetAwaiter().GetResult();
 }
Пример #12
0
 public async Task SendEmailAsync(MailMessage message)
 {
     var client           = new SendGrid.SendGridClient(emailOptions.SendGridApiKey);
     var from             = new EmailAddress(message.From.Address, message.From.DisplayName);
     var subject          = message.Subject;
     var to               = message.To.Select(t => new EmailAddress(t.Address, t.DisplayName));
     var htmlContent      = new Content("text/html", message.Body);
     var plainTextContent = Regex.Replace(htmlContent.Value, "<[^>]*>", "");
     var mail             = MailHelper.CreateSingleEmailToMultipleRecipients(from, to.ToList(), subject, plainTextContent, htmlContent.Value);
     await client.SendEmailAsync(mail);
 }
        public Task SendAsync(IdentityMessage message)
        {
            string sendGridApiKey = System.Configuration.ConfigurationManager.AppSettings["SendGrid.ApiKey"];

            SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridApiKey);
            SendGrid.Helpers.Mail.SendGridMessage sendgridMessage = new SendGrid.Helpers.Mail.SendGridMessage();
            sendgridMessage.AddTo(message.Destination);
            sendgridMessage.Subject = message.Subject;
            sendgridMessage.SetFrom("*****@*****.**", "WeirdEnsemble.com Administrator");
            sendgridMessage.AddContent("text/html", message.Body);
            sendgridMessage.SetTemplateId("9f449d8f-c608-4336-9cbf-8a73ca391f3e");
            return(client.SendEmailAsync(sendgridMessage));
        }
Пример #14
0
        public async Task SendAsync(IdentityMessage message)
        {
            var client = new SendGrid.SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var emailMessage = new SendGridMessage();

            emailMessage.From = new EmailAddress(ConfigurationManager.AppSettings["EmailAddress"],
                                                 ConfigurationManager.AppSettings["EmailDisplayName"]);
            emailMessage.AddTo(message.Destination);
            emailMessage.Subject     = message.Subject;
            emailMessage.HtmlContent = message.Body;

            await client.SendEmailAsync(emailMessage);
        }
Пример #15
0
        public Task SendEmail(string emailTo, string subject, string message)
        {
            _logger.LogInformation($"##Start## Sending email via SendGrid to: {emailTo} subject: {subject} message: {message}");
            var client          = new SendGrid.SendGridClient(_emailServiceOptions.RemoteServerAPI);
            var sendGridMessage = new SendGrid.Helpers.Mail.SendGridMessage {
                From = new SendGrid.Helpers.Mail.EmailAddress(_emailServiceOptions.UserId)
            };

            sendGridMessage.AddTo(emailTo);
            sendGridMessage.Subject     = subject;
            sendGridMessage.HtmlContent = message;
            client.SendEmailAsync(sendGridMessage);
            return(Task.CompletedTask);
        }
Пример #16
0
        public async Task <HttpStatusCode> SendEmailAsync(string fromEmail, string fromEmailName, string toEmail, string subject, string message)
        {
            var sendGridMessage = new SendGridMessage();

            sendGridMessage.AddTo(toEmail);
            sendGridMessage.From        = new EmailAddress(fromEmail, fromEmailName);
            sendGridMessage.Subject     = subject;
            sendGridMessage.HtmlContent = message;

            SendGrid.ISendGridClient transportWeb = new SendGrid.SendGridClient(_apiKey);
            SendGrid.Response        emailTask    = await transportWeb.SendEmailAsync(sendGridMessage);

            return(emailTask.StatusCode);
        }
        private Task configSendGridasync(IdentityMessage message)
        {
            var client = new SendGrid.SendGridClient(ConfigurationManager.AppSettings["SendGridKey"].ToString());

            var myMessage = new SendGridMessage();

            myMessage.AddTo(message.Destination);
            myMessage.From             = new EmailAddress("*****@*****.**", "MaildePrueba.");
            myMessage.Subject          = message.Subject;
            myMessage.PlainTextContent = message.Body;
            myMessage.HtmlContent      = message.Body;
            myMessage.SetClickTracking(false, false);
            return(client.SendEmailAsync(myMessage));
        }
Пример #18
0
        public Task SendEmail(string emailTo, string subject, string message)
        {
            _logger.LogInformation($"##Start## Wysyłanie wiadomości e-mail za pomocą usługi SendGrid do:{emailTo} temat:{subject} wiadomość:{message}");
            var client          = new SendGrid.SendGridClient(_emailServiceOptions.RemoteServerAPI);
            var sendGridMessage = new SendGrid.Helpers.Mail.SendGridMessage
            {
                From = new SendGrid.Helpers.Mail.EmailAddress(_emailServiceOptions.UserId)
            };

            sendGridMessage.AddTo(emailTo);
            sendGridMessage.Subject     = subject;
            sendGridMessage.HtmlContent = message;
            client.SendEmailAsync(sendGridMessage);             // wysłanie mail'a
            return(Task.CompletedTask);
        }
        private async void btnSend_Click(object sender, EventArgs e)
        {
            var client  = new SendGrid.SendGridClient(Constants.SEND_GRID_API_KEY);
            var subject = $"New Bug Report: {txtTitle.Text}";
            var content = $"New bug report: \n\nContact info: {txtEmail.Text}\n\nDescription: \n{txtDescription.Text}";

            var msg = MailHelper.CreateSingleEmail(
                new EmailAddress("*****@*****.**"),
                new EmailAddress(Constants.BUG_REPORT_EMAIL),
                subject, content, null);

            var response = await client.SendEmailAsync(msg);

            this.DialogResult = DialogResult.OK;
        }
Пример #20
0
        private Task configSendGridasync(IdentityMessage message)
        {
            var client = new SendGrid.SendGridClient(ConfigurationManager.AppSettings["SendGridKey"].ToString());

            var myMessage = new SendGridMessage();

            myMessage.AddTo(message.Destination);
            myMessage.From             = new EmailAddress("*****@*****.**", "David Santafe.");
            myMessage.Subject          = message.Subject;
            myMessage.PlainTextContent = message.Body;
            myMessage.HtmlContent      = message.Body;

            myMessage.SetClickTracking(false, false);
            return(client.SendEmailAsync(myMessage));
        }
Пример #21
0
        // Odosielanie emailu o tom, ze bola vytvorena aktivita
        private void SendActivityCreated(List <EmailAddress> mails, Activity activity, string link)
        {
            try
            {
                //Kontrola ci je mozne odoslat email
                if (string.IsNullOrEmpty(currUser.ApiKey))
                {
                    return;
                }

                EmailClient             client  = new EmailClient();
                string                  content = string.Empty;
                SendGrid.SendGridClient gridClient;
                if (!string.IsNullOrEmpty(link))
                {
                    gridClient = new SendGrid.SendGridClient(client.SetEnvironmentVar(currUser));
                    content    = $"Milí študenti, <br/> dňa {DateTime.Now.Date + DateTime.Now.TimeOfDay} Vám bola vytvorená aktivita {activity.ActivityName}," +
                                 $" <br/> ktorú je potrebné odovzdať do {activity.Deadline} <br/> {link}";
                }
                else
                {
                    gridClient = new SendGrid.SendGridClient(client.SetEnvironmentVar(currUser));
                    content    = $"Milí študenti, <br/> dňa {DateTime.Now.Date + DateTime.Now.TimeOfDay} Vám bola vytvorená aktivita {activity.ActivityName}," +
                                 $" <br/> ktorú je potrebné odovzdať do {activity.Deadline}";
                }

                EmailBody body = new EmailBody()
                {
                    HtmlContent      = content,
                    PlainTextContent = content,
                    To      = mails,
                    Subject = "Nová aktivita"
                };
                //Vytvorenie obsahu emailu, ktorym oznamujeme studentom, ze im bolo vytvorene hodnotenie a jeho nasledne odoslanie

                var msg = MailHelper.CreateSingleEmailToMultipleRecipients(MailHelper.StringToEmailAddress(currUser.Email), body.To, body.Subject, body.HtmlContent, body.HtmlContent);
                gridClient.SendEmailAsync(msg);

                Logger logger = new Logger();
                logger.LogEmail(DateTime.Now, body.To, body.Subject, body.HtmlContent, null);
            }
            catch (Exception ex)
            {
                Logger logger = new Logger();
                logger.LogError(ex);
                MessageBox.Show("Pri odosielaní emailu nastal problém.");
            }
        }
Пример #22
0
        public Task SendAsync(IdentityMessage message)
        {
            string apiKey = System.Configuration.ConfigurationManager.AppSettings["SendGrid.Key"];

            SendGrid.SendGridClient client = new SendGrid.SendGridClient(apiKey);

            SendGrid.Helpers.Mail.SendGridMessage mail = new SendGrid.Helpers.Mail.SendGridMessage();
            mail.SetFrom(new SendGrid.Helpers.Mail.EmailAddress {
                Name = "LawDoggs", Email = "*****@*****.**"
            });
            mail.AddTo(message.Destination);
            mail.Subject = message.Subject;
            mail.AddContent("text/plain", message.Body);
            mail.AddContent("text/html", message.Body);

            return(client.SendEmailAsync(mail));
        }
Пример #23
0
        public Task Execute(string apiKey, string subject, string message, string email)
        {
            var client = new SendGrid.SendGridClient(apiKey);
            var msg    = new SendGridMessage()
            {
                //THIS MUST MATCH A VERIFIED EMAIL ACCOUNT IN SENDGRID
                From             = new EmailAddress("*****@*****.**", Options.SendGridUser),
                Subject          = subject,
                PlainTextContent = message,
                HtmlContent      = message
            };

            msg.AddTo(new EmailAddress(email));
            // Disable click tracking.
            // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
            msg.SetClickTracking(true, true);
            return(client.SendEmailAsync(msg));
        }
Пример #24
0
        public void Send(EmailMessage message)
        {
            var msg = new SendGridMessage();

            msg.AddTo(message.Recipient);
            msg.From             = new EmailAddress("*****@*****.**", "Volley Management System");
            msg.Subject          = message.Subject;
            msg.PlainTextContent = message.Body;

            var web      = new SendGrid.SendGridClient(GetApiKey());
            var response = web.SendEmailAsync(msg);

            response.Wait();
            if (response.Result.StatusCode != HttpStatusCode.OK)
            {
                _logger.Write(LogLevelEnum.Error, $"Failed to send SendGrid email. Response was: ${response.Result}");
            }
        }
Пример #25
0
        /// <summary>
        /// Sends an email message through SendGrid.
        /// </summary>
        /// <param name="replyToAddress">Reply address ie. [email protected].</param>
        /// <param name="fromAddress">From address ie. [email protected].</param>
        /// <param name="recipientAddresses">List of addresses to send emails to.</param>
        /// <param name="subjectLine">Subject of the email message.</param>
        /// <param name="plainTextContent">Plain text version of the email content.</param>
        /// <param name="htmlContent">HTML content version of the email content.</param>
        /// <param name="categories">List of category strings for SendGrid analytics.</param>
        /// <returns></returns>
        public static async Task <bool> SendEmailMessage(EmailAddress replyToAddress, EmailAddress fromAddress, List <EmailAddress> recipientAddresses, string subjectLine, string plainTextContent, string htmlContent, List <string> categories)
        {
            try
            {
                var singleEmail =
                    MailHelper.CreateSingleEmailToMultipleRecipients(fromAddress, recipientAddresses, subjectLine, plainTextContent, htmlContent);
                singleEmail.SetReplyTo(replyToAddress);
                singleEmail.AddCategories(categories);

                var sendGridClient = new SendGrid.SendGridClient(AppConfiguration.SendGridApiKey);
                var sendEmail      = await sendGridClient.SendEmailAsync(singleEmail);

                return(sendEmail.StatusCode != System.Net.HttpStatusCode.Accepted);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Пример #26
0
        private async Task SendMailAsync(string e, string title, string body, string url = "")
        {
            SendGridMessage myMessage = new SendGridMessage();

            myMessage.AddTo(e);
            myMessage.From    = new EmailAddress(_appSettings.EmailFrom, _appSettings.NameEmailFrom);
            myMessage.Subject = title;


            myMessage.HtmlContent = body;
            if (!string.IsNullOrEmpty(url))
            {
                myMessage.Subject     += " " + url;
                myMessage.HtmlContent += "<span>Link referencia: " + url + "</span>";
            }

            var transportWeb = new SendGrid.SendGridClient(_appSettings.SendGridKey);
            var response     = await transportWeb.SendEmailAsync(myMessage);
        }
Пример #27
0
        public Task Execute(string apiKey, string subject, string message, string email)
        {
            var client = new SendGrid.SendGridClient(apiKey);
            var msg    = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", Options.SendGridUser),
                Subject          = subject,
                PlainTextContent = message,
                HtmlContent      = message
            };

            msg.AddTo(new EmailAddress(email));

            // Disable click tracking.
            // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
            msg.SetClickTracking(true, true);

            return(client.SendEmailAsync(msg));
        }
Пример #28
0
        private async Task configSendGridasync(IdentityMessage message)
        {
            var client = new SendGrid.SendGridClient("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");
            var msg    = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "Photo Studio"),
                Subject          = message.Subject,
                PlainTextContent = message.Body,
                HtmlContent      = message.Body
            };

            msg.AddTo(new EmailAddress(message.Destination));

            msg.SetClickTracking(false, false);

            var response = await client.SendEmailAsync(msg);

            var responseStatusCode = response.StatusCode;
        }
Пример #29
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (IdentityModels entities = new IdentityModels())
                {
                    var userStore = new UserStore <User>(entities);
                    var manager   = new UserManager <User>(userStore);

                    manager.UserTokenProvider = new EmailTokenProvider <User>();

                    var user = manager.FindByName(model.Email);
                    // If user has to activate his email to confirm his account, the use code listing below
                    //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                    //{
                    //    return Ok();
                    //}


                    string code = await manager.GeneratePasswordResetTokenAsync(user.Id);


                    string sendGridKey             = System.Configuration.ConfigurationManager.AppSettings["SendGrid.ApiKey"];
                    SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridKey);
                    SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage();
                    message.Subject = string.Format("Reset Password");
                    message.From    = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey");
                    message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(model.Email));

                    SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/html", string.Format("<a href=\"{0}\">Reset Password</a>", Request.Url.GetLeftPart(UriPartial.Authority) + "/MyAccount/ResetPassword/" + code + "?EmailAddress=" + model.Email));

                    message.AddContent(contents.Type, contents.Value);
                    SendGrid.Response response = await client.SendEmailAsync(message);

                    //await client.SendEmailAsync(user.Id, "Reset Password", $"Please reset your password by using this {code}");
                    return(RedirectToAction("ResetSent"));
                }
            }
            return(View());

            // If we got this far, something failed, redisplay form
        }
Пример #30
0
        //overload with what you want to show in the email.
        public void SendConfirmation(string email)
        {
            try
            {
                var myMessage = new SendGridMessage
                {
                    From = new EmailAddress("*****@*****.**", "Limitless")
                };


                myMessage.AddTo(email);
                string subject = "Booking Receipt for reservation: ";
                string body    = (
                    "Dear " + "<br/>"
                    + "<br/>"
                    + "Please find below your details of your recent reservation: "
                    + "<br/>"
                    + "<br/>" + "Total Price       :" + "R"
                    + "<br/>" + "Check-In Date     :"
                    + "<br/>" + "Check-Out Date     :"
                    + "<br/>" + "Number Of Days     :"
                    + "<br/>" + "Number Of People  :" +
                    "<br/>" +
                    "<br/>" +
                    "<br/>" +

                    "Many Thanks, " +
                    "<br/>" +
                    "Limitless Developers Team ");

                myMessage.Subject     = subject;
                myMessage.HtmlContent = body;

                var transportWeb = new SendGrid.SendGridClient("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");

                transportWeb.SendEmailAsync(myMessage);
            }
            catch (Exception x)
            {
                Console.WriteLine(x);
            }
        }