static async Task Execute()
        {
            var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage();
            var people = new List <Person>
            {
                new Person {
                    FirstName = "First1", LastName = "Last1", Email = "*****@*****.**"
                },
                new Person {
                    FirstName = "First2", LastName = "Last2", Email = "*****@*****.**"
                },
                new Person {
                    FirstName = "First3", LastName = "Last3", Email = "*****@*****.**"
                }
            };

            msg.SetFrom(new EmailAddress("*****@*****.**", "Example User"));
            msg.SetSubject("Test Subject 1");
            msg.AddContent(MimeType.Text, "Hello -firstname- -lastname-");
            var tos = new List <EmailAddress>();
            var personalizationIndex = 0;

            foreach (var person in people)
            {
                tos.Add(new EmailAddress(person.Email, person.FirstName));
                msg.AddSubstitution("-firstname-", person.FirstName, personalizationIndex);
                msg.AddSubstitution("-lastname-", person.LastName, personalizationIndex);
                personalizationIndex++;
            }
            msg.AddTos(tos);
            var response = await client.SendEmailAsync(msg);
        }
Exemplo n.º 2
0
        public async Task SendPenaltyInvoice(Penalty penalty)
        {
            Parking parking = await context.Parking.FindAsync(penalty.ParkingId);

            DateTime penaltyTime = DateTime.Now;
            DateTime startTime   = DateTime.Parse(Convert.ToString(parking.CreatedAt));
            DateTime expectedEnd = startTime.AddHours(Convert.ToDouble(parking.ParkedHours));

            //This key is for authentication in SendGrid API
            var sendGridAPIKey = Environment.GetEnvironmentVariable("SENDGRID_KEY");

            //Initializing new instance of the API client
            var mailClient = new SendGridClient(sendGridAPIKey);

            //Initializing new message
            var message = new SendGridMessage()
            {
                From = new EmailAddress("*****@*****.**", "ParkKL"),
            };

            message.SetTemplateId("a1049d0f-08ed-4a78-8b3e-d1e890b41ec0");
            message.AddSubstitution("-PLATE-", parking.CarPlateNumber);
            message.AddSubstitution("-LOCATION-", parking.LocationName);
            message.AddSubstitution("-ISSUETIME-", penaltyTime.ToString("g"));
            message.AddSubstitution("-ENDTIME-", expectedEnd.ToString("g"));
            message.AddSubstitution("-EXCEED-", penalty.ExceededHours);

            message.AddTo(new EmailAddress(penalty.Email, "User"));

            //Sending the E-mail message
            var response = await mailClient.SendEmailAsync(message);
        }
Exemplo n.º 3
0
        public static Task EnviarRedefinicaoSenha(string email, string nome, string url)
        {
            var             username  = Properties.Resources.userEmail;
            var             pswd      = Properties.Resources.userSenha;
            SendGridMessage myMessage = new SendGridMessage();

            myMessage.AddTo(email);
            myMessage.From = new MailAddress("*****@*****.**", "Lance Um Desafio");
            myMessage.EnableTemplateEngine("c03dd00b-eaf1-42f7-9047-5f026f42163f"); // Redefinição De Senha
            myMessage.Subject = "Lance Um Desafio - Redefinição De Senha";
            myMessage.Html    = "Olá";
            myMessage.Text    = "Olá";

            myMessage.AddSubstitution("[USER_NAME]", new List <string> {
                nome
            });
            myMessage.AddSubstitution("[URL_RESET]", new List <string> {
                url
            });
            var credenciais   = new NetworkCredential(username, pswd);
            var transporteWeb = new Web(credenciais);


            if (transporteWeb != null)
            {
                return(transporteWeb.DeliverAsync(myMessage));
            }
            else
            {
                return(Task.FromResult(0));
            }
        }
Exemplo n.º 4
0
        public async Task SendTopUpReceipt(Wallet wallet, string Id, string Amount)
        {
            User user = await context.Users.FindAsync(Id);

            DateTime paymentTime = DateTime.Now;

            //This key is for authentication in SendGrid API
            var sendGridAPIKey = Environment.GetEnvironmentVariable("SENDGRID_KEY");

            //Initializing new instance of the API client
            var mailClient = new SendGridClient(sendGridAPIKey);

            //Initializing new message
            var message = new SendGridMessage()
            {
                From = new EmailAddress("*****@*****.**", "ParkKL"),
            };

            //Configuring the E-mail message to fit a saved template
            message.SetTemplateId("7f25958d-a1bb-47e8-95aa-59a0e308373e");
            message.AddSubstitution("-FIRST-", user.FirstName);
            message.AddSubstitution("-DATE-", paymentTime.ToString("g"));
            message.AddSubstitution("-AMOUNT-", Amount);
            message.AddSubstitution("-BALANCE-", wallet.Balance.ToString());
            message.AddTo(new EmailAddress(wallet.Email, "User"));

            //Sending the E-mail message
            var response = await mailClient.SendEmailAsync(message);
        }
Exemplo n.º 5
0
        public async Task <OperationResult> Execute(string apiKey, string subject, string email, string templateId = null, Dictionary <string, string> arguments = null)
        {
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage()
            {
                // should be a domain other than yahoo.com, outlook.com, hotmail.com, gmail.com
                From       = new EmailAddress("*****@*****.**", "Azure Quest Workshop"),
                Subject    = subject,
                TemplateId = templateId
            };

            msg.AddSubstitution("<%subject%>", subject);

            if (arguments != null)
            {
                arguments.ToList().ForEach(pair => { msg.AddSubstitution(pair.Key, pair.Value); });
            }

            msg.AddTo(new EmailAddress(email));
            msg.SetOpenTracking(true, "<%tracking%>");
            msg.SetClickTracking(true, true);
            msg.SetSubscriptionTracking(true);

            var response = await client.SendEmailAsync(msg);

            return(new OperationResult(true)
            {
                Tag = response
            });
        }
        public async Task <string> SendNewUserInvitation([FromBody] SetPasswordMessage notification)
        {
            var msg = new SendGridMessage();

            msg.AddSubstitution("-username-", notification.EventBody.Username);
            msg.AddSubstitution("-passwordtoken-", notification.EventBody.PasswordRenewalAccessToken);
            msg.AddSubstitution("-passwordverificationcode-", notification.EventBody.PasswordRenewalVerificationCode);
            return(await SendSendGrid(notification, msg));
        }
Exemplo n.º 7
0
            private SendGridMessage BuildEmailMessage(EmailSettings settings, Models.SubmissionData submissionData)
            {
                // 1. Buld SendGrid message with params and substitutions
                var msg = new SendGridMessage();

                msg.SetFrom(new EmailAddress(settings.FromAddress, settings.FromName));
                msg.AddTo(new EmailAddress(settings.ToAddress));

                if (!string.IsNullOrEmpty(settings.TemplateId))
                {
                    msg.SetTemplateId(settings.TemplateId);
                }

                if (string.IsNullOrEmpty(msg.TemplateId))
                {
                    var plainTextContent = settings.TextContent;

                    msg.SetSubject(settings.Subject);
                    msg.AddContent(System.Net.Mime.MediaTypeNames.Text.Plain, plainTextContent);
                }
                else
                {
                    foreach (var s in submissionData.Fields)
                    {
                        msg.AddSubstitution($"-{s.Name}-", s.Value);
                    }
                }

                return(msg);
            }
Exemplo n.º 8
0
        static async Task Execute()
        {
            var sendGridMessage = new SendGridMessage();

            byte[] data          = Convert.FromBase64String(_base64ApiKey);
            string decodedString = Encoding.UTF8.GetString(data);
            var    client        = new SendGridClient(decodedString);

            sendGridMessage.From = new EmailAddress("*****@*****.**", "HRPayroll");
            foreach (MailAddress mailAddress in _email.To)
            {
                sendGridMessage.AddTo(mailAddress.Address, mailAddress.DisplayName);
                sendGridMessage.AddSubstitution("#Name#", mailAddress.DisplayName);
            }

            sendGridMessage.Subject     = _email.Subject;
            sendGridMessage.HtmlContent = _email.Body;
            sendGridMessage.TemplateId  = "661fbfd5-e6ed-42c7-b436-adc9651c0db8";

            var response = await client.SendEmailAsync(sendGridMessage);

            foreach (MailAddress emailAddress in _email.To)
            {
                new EventLogger(
                    string.Format("Email logged to \"{0}\" with subject \"{1}\" with status code \"{2}\"",
                                  emailAddress.DisplayName, _email.Subject, response.StatusCode.ToString()), Severity.Event);
            }
        }
Exemplo n.º 9
0
 /// <summary>
 /// Add any substitutions we have to the message
 /// </summary>
 /// <param name="message"></param>
 /// <param name="subs"></param>
 private static void AddSubstitutions(SendGridMessage message, Dictionary <string, string> subs)
 {
     foreach (var pair in subs)
     {
         message.AddSubstitution(pair.Key, pair.Value);
     }
 }
Exemplo n.º 10
0
        public async Task <IActionResult> ForgotPassword(LoginViewModel vm)
        {
            var user = await _userManager.FindByNameAsync(vm.UserName);

            var confirmationCode = await _userManager.GeneratePasswordResetTokenAsync(user);

            var callbackUrl = Url.Action(
                controller: "Home",
                action: "ResetPassword",
                values: new { userId = user.Id, code = confirmationCode },
                protocol: Request.Scheme);
            var client = new SendGridClient("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");
            // Initiate a new send grid message.
            var msg = new SendGridMessage
            {
                From = new EmailAddress(vm.UserName, "KingPim Reset Password")
            };

            // Add the receiver.
            msg.AddTo("*****@*****.**");
            // Add template id the email should use.
            msg.TemplateId = "63dce31a-4040-45d9-9a2b-a63495a16c5f";
            // Set the substitution tag value.
            msg.AddSubstitution("substitutionLink", callbackUrl);
            // Send the email async and get the response from API.
            var response = client.SendEmailAsync(msg).Result;

            TempData["CheckYourEmail"] = "Your reset password link was sent to your email.";
            return(RedirectToAction(nameof(Index)));
        }
        public async Task <string> SendQuoteSurvey(PolicyDTO policy)
        {
            string batchId = await GetBatchId();

            string fullName = $"{policy.Contact.FirstName} {policy.Contact.LastName}";

            SendGridMessage message = new SendGridMessage()
            {
                To      = new MailAddress[] { new MailAddress(policy.Contact.EmailAddress, fullName), },
                Subject = "RAC Bicycle Insurance Survey",
                From    = new MailAddress(ExternalEmailsFrom, "RAC Bicycle Insurance"),
                Html    = $"Hi",
                Text    = $"Hi"
            };

            message.Headers["batch_id"] = batchId;
            message.SetSendAt(DateTime.UtcNow.AddMinutes(10));
            message.EnableTemplateEngine(_surveyTemplateId);
            message.AddSubstitution("%%name%%", new List <string> {
                fullName
            });

            SendGrid.Web transportWeb = new SendGrid.Web(_sendGridApiKey);

            await transportWeb.DeliverAsync(message);

            return("Hello");
        }
Exemplo n.º 12
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);
            }
        }
Exemplo n.º 13
0
        public void SendErrorLogMessage(string _subject, string _FullErrorMessage)
        {
            try
            {
                var errorTemplateSendGridId = System.Configuration.ConfigurationSettings.AppSettings["SENDGRID_ERRORTEMPLATEID"];

                var fromError = System.Configuration.ConfigurationSettings.AppSettings["SENDGRID_ERROR_EMAILFROM"];

                var msg = new SendGridMessage()
                {
                    From    = new EmailAddress(fromError, "ONR Video Error Team"),
                    Subject = _subject
                };
                var toError = System.Configuration.ConfigurationSettings.AppSettings["SENDGRID_ERROR_EMAILTO"];
                msg.AddTo(new EmailAddress("*****@*****.**", ""));
                msg.SetTemplateId(errorTemplateSendGridId);
                msg.AddSubstitution("FullErrorMessage", _FullErrorMessage);


                SendMail(msg).Wait();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(string.Format("Error when creating log error emailEmail {0} . Error Information :  {1}, {2}", _subject, ex.Message, ex.InnerException));
            }
            //writeMessage(_message, LogType.Message);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> ForgottenPassword(LoginViewModel vm)
        {
            var user = await _userManager.FindByNameAsync(vm.UserName);

            var confCode = await _userManager.GeneratePasswordResetTokenAsync(user);

            var link = Url.Action("ResetPassword", "Home", new { userId = user.Id, code = confCode },
                                  protocol: Request.Scheme);

            // The new SendGridClient with the API-key:
            var client = new SendGridClient("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");

            // The message from SendGrid:
            var msg = new SendGridMessage
            {
                From = new EmailAddress(vm.UserName, "Password Reset")
            };

            // The reciever of the mail:
            msg.AddTo(vm.UserName);
            // The template id the email should use from SendGrid:
            msg.TemplateId = "6a88245c-ff27-427c-817e-556d50213a82";

            // Set the substitution tag value. This will create a link to reset password.
            msg.AddSubstitution("substitutionLink", link);
            // Send the email async and get the response from API.
            var response = client.SendEmailAsync(msg).Result;

            return(RedirectToAction(nameof(Index)));
        }
Exemplo n.º 15
0
        public async Task <bool> SendPasswordResetLink(string toEmail, string toName, string url)
        {
            var msg = new SendGridMessage()
            {
                From       = new EmailAddress("*****@*****.**", "RunIt"),
                Subject    = "Reset password",
                TemplateId = "3291d65a-ac51-442e-b359-74c30e3c9c04"
            };

            msg.AddTo(new EmailAddress(toEmail, toName));
            msg.AddSubstitution("{{name}}", toName);
            msg.AddSubstitution("{{link}}", url);

            var response = await client.SendEmailAsync(msg);

            return(await CheckResponse(response));
        }
Exemplo n.º 16
0
        public async Task SendParkingReceipt(Wallet wallet, string Id, string Amount, string parkingId)
        {
            User user = await context.Users.FindAsync(Id);

            Parking parking = await context.Parking.FindAsync(parkingId);

            DateTime paymentTime = DateTime.Now;

            //This key is for authentication in SendGrid API
            var sendGridAPIKey = Environment.GetEnvironmentVariable("SENDGRID_KEY");

            //Initializing new instance of the API client
            var mailClient = new SendGridClient(sendGridAPIKey);

            //Initializing new message
            var message = new SendGridMessage()
            {
                From = new EmailAddress("*****@*****.**", "ParkKL"),
            };

            //Configuring the E-mail message to fit a saved template
            message.SetTemplateId("12ee3b1e-cca1-4844-ad8b-d0f78fd87299");
            message.AddSubstitution("-FIRST-", user.FirstName);
            message.AddSubstitution("-DATE-", paymentTime.ToString("g"));
            message.AddSubstitution("-LOCATION-", parking.LocationName);
            message.AddSubstitution("-PLATE-", parking.CarPlateNumber);
            message.AddSubstitution("-DURATION-", parking.ParkedHours.ToString());
            message.AddSubstitution("-AMOUNT-", Amount);
            message.AddSubstitution("-BALANCE-", wallet.Balance.ToString());
            message.AddTo(new EmailAddress(wallet.Email, "User"));

            //Sending the E-mail message
            var response = await mailClient.SendEmailAsync(message);
        }
        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]);
                }
            }
        }
Exemplo n.º 18
0
        private SendGridMessage BuildOrderMessage(OrderEventBody eventBody)
        {
            var msg = new SendGridMessage();

            msg.AddSubstitution("-firstname-", eventBody.Order.FromUser.FirstName);
            msg.AddSubstitution("-lastname-", eventBody.Order.FromUser.LastName);
            msg.AddSubstitution("-orderid-", eventBody.Order.ID);
            msg.AddSubstitution("-datesubmitted-", eventBody.Order.DateSubmitted.ToString());
            msg.AddSubstitution("-subtotal-", eventBody.Order.Subtotal.ToString());
            msg.AddSubstitution("-tax-", eventBody.Order.TaxCost.ToString());
            msg.AddSubstitution("-shipping-", eventBody.Order.ShippingCost.ToString());
            msg.AddSubstitution("-total-", eventBody.Order.Total.ToString());
            msg.AddSubstitution("-lineitemcount-", eventBody.Order.LineItemCount.ToString());
            return(msg);
        }
Exemplo n.º 19
0
        private SendGridMessage CreateDefaultMessage(string templateId)
        {
            var message = new SendGridMessage
            {
                From             = new EmailAddress(_globalSettings.Mail.ReplyToEmail, _globalSettings.SiteName),
                HtmlContent      = " ",
                PlainTextContent = " "
            };

            if (!string.IsNullOrWhiteSpace(templateId))
            {
                message.TemplateId = templateId;
            }

            message.AddSubstitution("{{siteName}}", _globalSettings.SiteName);
            message.AddSubstitution("{{baseVaultUri}}", _globalSettings.BaseVaultUri);

            return(message);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Sends the mail batch using the SendGrid API
        /// </summary>
        /// <param name="mail">The mail.</param>
        /// <param name="recipients">The recipients.</param>
        /// <param name="onlyTestDontSendMail">if set to <c>true</c> [only test dont send mail].</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool SendMailBatch(MailInformation mail, IEnumerable <JobWorkItem> recipients, bool onlyTestDontSendMail)
        {
            var settings = GetSettings();

            if (recipients == null || recipients.Any() == false)
            {
                throw new ArgumentException("No workitems", "recipients");
            }

            if (recipients.Count() > 1000)
            {
                throw new ArgumentOutOfRangeException("recipients", "SendGrid supports maximum 1000 recipients per batch send.");
            }

            var msg = new SendGridMessage();

            msg.From    = new MailAddress(mail.From);
            msg.Subject = mail.Subject;
            msg.Html    = mail.BodyHtml;
            msg.Text    = mail.BodyText;

            // Add recipinets to header, to hide other recipients in to field.
            List <string> addresses = recipients.Select(r => r.EmailAddress).ToList();

            msg.Header.SetTo(addresses);
            msg.AddSubstitution("%recipient%", addresses);
            // To send message we need to have a to address, set that to from
            msg.To = new MailAddress[] { msg.From };

            if (mail.EnableTracking)
            {
                // true indicates that links in plain text portions of the email
                // should also be overwritten for link tracking purposes.
                msg.EnableClickTracking(true);
                msg.EnableOpenTracking();
            }

            if (mail.CustomProperties.ContainsKey("SendGridCategory"))
            {
                string category = mail.CustomProperties["SendGridCategory"] as string;
                if (string.IsNullOrEmpty(category) == false)
                {
                    msg.SetCategory(category);
                }
            }

            var credentials = new NetworkCredential(settings.Username, settings.Password);

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

            transportWeb.Deliver(msg);

            return(true);
        }
Exemplo n.º 21
0
 private void ProcessTemplate(SendGridMessage message, IMailingTemplate mailingTemplate)
 {
     if (mailingTemplate != null)
     {
         message.SetTemplateId(mailingTemplate.TemplateId);
         foreach (var substitution in mailingTemplate.Substitution)
         {
             message.AddSubstitution(substitution.Key, substitution.Value?.ToString() ?? "");
         }
     }
 }
Exemplo n.º 22
0
        private SendGridMessage GetMessage(INotification notification)
        {
            var applicationName = _appSettings.GetSetting(AppSettingKey.ApplicationName);

            var message = new SendGridMessage();

            message.From    = new MailAddress(_appSettings.GetSetting(AppSettingKey.FromEmail), applicationName);
            message.Subject = notification.Subject;
            message.AddTo(GetEmailTo(notification.EmailTo));

            message.EnableTemplateEngine(notification.TemplateName);

            message.Text = "   ";

            foreach (var templateContent in notification.TemplateContent)
            {
                message.AddSubstitution(GetReplacementTag(templateContent.Key), templateContent.Value.PutIntoList());
            }
            message.AddSubstitution(GetReplacementTag("application_name"), applicationName.PutIntoList());
            return(message);
        }
Exemplo n.º 23
0
        public async Task SendRemindersAsync(List <string> emailList, Occurrence occurrence)
        {
            Opportunity opportunity = occurrence.Opportunity;
            //            string messageText = "Hey There! This is a reminder for your upcoming volunteer gig. " +
            //                         "Please reply to this email if you can no longer make the event.";

            string messageText = "Volunteers: " + String.Join("\n", emailList);

            SendGridMessage sendGridMessage = new SendGridMessage()
            {
                From             = new EmailAddress(FromEmail, "Volly Team"),
                Subject          = "Volly Reminder: " + opportunity.Name,
                TemplateId       = "d-70aba37e40834a89b8afe3a1a9567bcd",
                HtmlContent      = messageText,
                PlainTextContent = messageText
            };

            DateTime startTime = VollyConstants.ConvertFromUtc(occurrence.StartTime);
            DateTime endTime   = VollyConstants.ConvertFromUtc(occurrence.EndTime);

            sendGridMessage.AddSubstitution(":start", startTime.ToShortDateString() + " " + startTime.ToShortTimeString());
            sendGridMessage.AddSubstitution(":end", endTime.ToShortDateString() + " " + endTime.ToShortTimeString());
            sendGridMessage.AddSubstitution(":description", opportunity.Description);
            sendGridMessage.AddSubstitution(":address", opportunity.Address);
            sendGridMessage.AddSubstitution(":name", opportunity.Name);
            sendGridMessage.AddSubstitution(":image", opportunity.ImageUrl);

            var client = new SendGridClient(SendgridApiKey);

            sendGridMessage.AddTo(VollyConstants.AliceEmail);

            Response response = await client.SendEmailAsync(sendGridMessage);
        }
Exemplo n.º 24
0
        //This method will send account registration confirmation
        public async Task SendConfirmationEmail(User item)
        {
            //This key is for authentication in SendGrid API
            var sendGridAPIKey = Environment.GetEnvironmentVariable("SENDGRID_KEY");

            //Initializing new instance of the API client
            var mailClient = new SendGridClient(sendGridAPIKey);

            //Initializing new message
            var message = new SendGridMessage()
            {
                From = new EmailAddress("*****@*****.**", "ParkKL"),
            };

            //Initializing claims that will be included with the E-mail
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, item.Id),
                new Claim(JwtRegisteredClaimNames.Email, item.Email)
            };

            //Creating new JWT Security Token
            ClaimsIdentity          claimsID = new ClaimsIdentity(claims);
            JwtSecurityTokenHandler handler  = new JwtSecurityTokenHandler();
            JwtSecurityToken        token    = handler.CreateToken(null, null, claimsID,
                                                                   null, null, null);
            string encodedToken = handler.WriteToken(token);

            //Configuring the E-mail message to fit a saved template
            message.SetTemplateId("503f2077-dd34-43c1-994f-be61adbe6fd7");
            message.AddSubstitution("-EMAIL-", item.Email);
            message.AddSubstitution("-FIRST-", item.FirstName);
            message.AddSubstitution("-TOKEN-", encodedToken);
            message.AddTo(new EmailAddress(item.Email, "User"));

            //Sending the E-mail message
            var response = await mailClient.SendEmailAsync(message);
        }
Exemplo n.º 25
0
        public void SendTeamVidEmail(ONRVideo.ModelTeamEmail _teamModelEmail)
        {
            try
            {
                var msg = new SendGridMessage()
                {
                    From    = new EmailAddress(_teamModelEmail.From, _teamModelEmail.FromName),
                    Subject = _teamModelEmail.Subject
                };
                List <EmailAddress> emailList = new List <EmailAddress>();
                string toNames = string.Empty; //Holds the names that the amil will be adressed to ex: Dear Eric, Mike and Julie

                foreach (Volunteer volunteer in _teamModelEmail.TeamMembers)
                {
                    emailList.Add(new EmailAddress(volunteer.email, string.Format("{0} {1}", volunteer.firstName, volunteer.lastName)));
                    toNames += string.Format("{0}, ", volunteer.firstName);
                }
                msg.AddTos(emailList);

                //msg.AddTo(new EmailAddress("*****@*****.**", ""));
                msg.SetTemplateId(_teamModelEmail.EmailTemplateId);


                msg.AddSubstitution("ToNames", toNames);
                msg.AddSubstitution("TeamNumber", _teamModelEmail.TeamNumber.ToString());
                msg.AddSubstitution("SoireeDate", _teamModelEmail.Soiree.ToLongDateString());
                msg.AddSubstitution("YoutubeID", _teamModelEmail.YoutubeVideoID);


                msg.SetClickTracking(true, true);

                SendMail(msg).Wait();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(string.Format("Error when creating email  for team  {0}. Error Information :  {1}, {2}", _teamModelEmail.TeamNumber, ex.Message, ex.InnerException));
            }
        }
Exemplo n.º 26
0
        private SendGridMessage CreateDefaultMessage(string templateId)
        {
            var message = new SendGridMessage
            {
                From = new MailAddress(_globalSettings.Mail.ReplyToEmail, _globalSettings.SiteName),
                Html = " ",
                Text = " "
            };

            if (!string.IsNullOrWhiteSpace(templateId))
            {
                message.EnableTemplateEngine(templateId);
            }

            message.AddSubstitution("{{siteName}}", new List <string> {
                _globalSettings.SiteName
            });
            message.AddSubstitution("{{baseVaultUri}}", new List <string> {
                _globalSettings.BaseVaultUri
            });

            return(message);
        }
Exemplo n.º 27
0
        public async Task <IActionResult> ForgottenPassword(LoginViewModel vm, string apiKey)
        {
            var user = await _userManager.FindByNameAsync(vm.UserName);

            var confCode = await _userManager.GeneratePasswordResetTokenAsync(user);

            var callbackUrl = Url.Action(
                controller: "Home",
                action: "ResetPassword",
                values: new { userId = user.Id, code = confCode },
                protocol: Request.Scheme);

            // The new SendGridClient with the API-key:
            var client = new SendGridClient(apiKey);


            // The message from SendGrid:
            var msg = new SendGridMessage
            {
                From = new EmailAddress("*****@*****.**", "Password Reset")
            };

            // The reciever of the mail:
            msg.AddTo(vm.UserName);

            // The template id the email should use from SendGrid:
            msg.TemplateId = "8cfda5bc-a0a7-47da-9be7-b942c7a3669a";

            // Set the substitution tag values from SendGrid Template:
            msg.AddSubstitution("forgottenPasswordLink", callbackUrl);
            msg.AddSubstitution("userName", vm.UserName);

            // Send the email async and get the response from API:
            var response = client.SendEmailAsync(msg).Result;

            return(RedirectToAction(nameof(Index)));
        }
        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]);
                }
            }
        }
Exemplo n.º 29
0
        public static async Task <Response> SendLegacy(EmailAddress from, List <EmailAddress> to, string subject, string templateId, IDictionary <string, string> substitutions, string attachmentName = "", string attachmentBase64String = "")
        {
            var msg = new SendGridMessage();

            msg.SetFrom(from);
            msg.AddTos(to);
            msg.SetSubject(subject);
            msg.SetTemplateId(templateId);
            if (attachmentName != string.Empty && attachmentBase64String != string.Empty)
            {
                msg.AddAttachment(attachmentName, attachmentBase64String);
            }
            substitutions.ToList().ForEach(sub => msg.AddSubstitution(sub.Key, sub.Value));
            return(await Send(msg));
        }
Exemplo n.º 30
0
        public async Task SendEmailAsync(string emailAddress, string url)
        {
            var apiKey  = Environment.GetEnvironmentVariable("SG_YASC_API");
            var client  = new SendGridClient(apiKey);
            var from    = new EmailAddress("*****@*****.**", "No Reply");
            var subject = url;
            var to      = new EmailAddress(emailAddress);
            var sgMsg   = new SendGridMessage();

            sgMsg.SetFrom(from);
            sgMsg.SetSubject(subject);
            sgMsg.AddTo(to);
            sgMsg.SetTemplateId("e08f6cd0-5b93-429e-9695-18640cb6e78a");
            sgMsg.AddSubstitution("-domain-", url);

            await client.SendEmailAsync(sgMsg);
        }