Ejemplo n.º 1
0
        private static async Task HelloEmail()
        {
            String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
            dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

            Email from = new Email("*****@*****.**");
            String subject = "Hello World from the SendGrid CSharp Library";
            Email to = new Email("*****@*****.**");
            Content content = new Content("text/plain", "Textual content");
            Mail mail = new Mail(from, subject, to, content);
            Email email = new Email("*****@*****.**");
            mail.Personalization[0].AddTo(email);

            // If you want to use a transactional [template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html),
            // the following code will replace the above subject and content. The sample code assumes you have defined
            // substitution variables [KEY_1] and [KEY_2], to be replaced by VALUE_1 and VALUE_2 respectively, in your template.
            //mail.TemplateId = "TEMPLATE_ID";
            //mail.Personalization[0].AddSubstitution("[KEY_1]", "VALUE_1");
            //mail.Personalization[0].AddSubstitution("[KEY_2]", "VALUE_2");

            dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers.ToString());

            Console.WriteLine(mail.Get());
            Console.ReadLine();

        }
Ejemplo n.º 2
0
        public async Task SendHtmlEmail(string subject, string toEmail, string content)
        {
            string apiKey = _configurationService.Email.ApiKey;
            dynamic sg = new SendGridAPIClient(apiKey);

            Email from = new Email(_configurationService.Email.From);
            Email to = new Email(toEmail);
            Content mailContent = new Content("text/html", content);
            Mail mail = new Mail(from, subject, to, mailContent);

            var personalization = new Personalization();
            personalization.AddTo(to);

            if (_configurationService.Email.Bcc != null && _configurationService.Email.Bcc.Any())
            {

                foreach (var bcc in _configurationService.Email.Bcc)
                {
                    personalization.AddBcc(new Email(bcc));
                }
                mail.AddPersonalization(personalization);
            }

            dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());

            if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
            {
                var responseMsg = response.Body.ReadAsStringAsync().Result;
                _logger.Error($"Unable to send email: {responseMsg}");
            }
        }
Ejemplo n.º 3
0
        public ActionResult ForgotPassword(ForgotPasswordModel model)
        {
            string email      = model.EmailAddress;
            string resetToken = WebMatrix.WebData.WebSecurity.GeneratePasswordResetToken(model.EmailAddress);
            string resetUrl   = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/CompleteForgotPassword?resetToken" + resetToken;


            string apiKey = ConfigurationManager.AppSettings["SendGrid.Key"];

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

            SendGrid.Helpers.Mail.Email from = new SendGrid.Helpers.Mail.Email("*****@*****.**");
            string subject = "Couture Events: Password Reset!";

            SendGrid.Helpers.Mail.Email to = new SendGrid.Helpers.Mail.Email(model.EmailAddress);

            Content content = new Content("text/html", " ");
            Mail    mail    = new Mail(from, subject, to, content);

            mail.TemplateId = "be1b809e-4cc5-425c-8b7e-cc9846b0777f";
            mail.Personalization[0].AddSubstitution("-token-", resetToken);
            mail.Personalization[0].AddSubstitution("-url-", resetUrl);

            client.client.mail.send.post(requestBody: mail.Get());
            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 4
0
        public void AddCc(Email email)
        {
            if (Ccs == null)
                Ccs = new List<Email>();

            Ccs.Add(email);
        }
        public async Task SendAsync(IdentityMessage message)
        {
            //var myMessage = new SendGridMessage();
            //myMessage.AddTo(message.Destination);
            //myMessage.From = new MailAddress("*****@*****.**", "fzrain");
            //myMessage.Subject = message.Subject;
            //myMessage.Text = message.Body;
            //myMessage.Html = message.Body;

            //var credentials = new NetworkCredential("fzy55601", "fzy86087108");
            //// Create a Web transport for sending email.
            //var transportWeb = new Web(credentials);
            //// Send the email.
            //await transportWeb.DeliverAsync(myMessage);

            String apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY", EnvironmentVariableTarget.User);
            dynamic sg = new SendGridAPIClient(apiKey);

            Email from = new Email("*****@*****.**");
            String subject = "Hello World from the SendGrid CSharp Library";
            Email to = new Email("*****@*****.**");
            Content content = new Content("text/plain", "Textual content");
            Mail mail = new Mail(from, subject, to, content);

            dynamic response = sg.client.mail.send.post(requestBody: mail.Get());
        }
Ejemplo n.º 6
0
        public void TestHelloEmail()
        {
            Mail mail = new Mail();

            Email email = new Email();
            email.Address = "*****@*****.**";
            mail.From = email;

            Personalization personalization = new Personalization();
            email = new Email();
            email.Address = "*****@*****.**";
            personalization.AddTo(email);
            mail.AddPersonalization(personalization);

            mail.Subject = "Hello World from the SendGrid CSharp Library";

            Content content = new Content();
            content.Type = "text/plain";
            content.Value = "Textual content";
            mail.AddContent(content);
            content = new Content();
            content.Type = "text/html";
            content.Value = "<html><body>HTML content</body></html>";
            mail.AddContent(content);

            String ret = mail.Get();
            String final = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(ret),
                                Formatting.None,
                                new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include });
            Assert.AreEqual(final, "{\"from\":{\"email\":\"[email protected]\"},\"subject\":\"Hello World from the SendGrid CSharp Library\",\"personalizations\":[{\"to\":[{\"email\":\"[email protected]\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Textual content\"},{\"type\":\"text/html\",\"value\":\"<html><body>HTML content</body></html>\"}]}");
        }
Ejemplo n.º 7
0
        public void AddBcc(Email email)
        {
            if (Bccs == null)
                Bccs = new List<Email>();

            Bccs.Add(email);
        }
Ejemplo n.º 8
0
        public ActionResult Checkout(ProposalModel model)
        {
            string apiKey = ConfigurationManager.AppSettings["SendGrid.Key"];

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

            SendGrid.Helpers.Mail.Email from = new SendGrid.Helpers.Mail.Email("*****@*****.**");
            string subject = "Couture Events: New Client!";

            SendGrid.Helpers.Mail.Email to = new SendGrid.Helpers.Mail.Email("*****@*****.**");

            Content content = new Content("text/html", " ");
            Mail    mail    = new Mail(from, subject, to, content);

            mail.TemplateId = "13a5ec2f-0260-4134-a3a2-aeacbe6882ec";
            mail.Personalization[0].AddSubstitution("-brideName-", model.Customer.BrideFirstName + "  " + model.Customer.BrideLastName);
            mail.Personalization[0].AddSubstitution("-groomName-", model.Customer.GroomFirstName + " " + model.Customer.GroomLastName);
            mail.Personalization[0].AddSubstitution("-phoneNumber-", model.Customer.PhoneNumber);
            mail.Personalization[0].AddSubstitution("-email-", model.Customer.Email);
            mail.Personalization[0].AddSubstitution("-weddingDate-", model.Customer.WeddingDate.ToString());
            mail.Personalization[0].AddSubstitution("-numberOfGuests-", model.Customer.NumberOfGuests.ToString());
            mail.Personalization[0].AddSubstitution("-serviceName-", model.Service.Name);
            mail.Personalization[0].AddSubstitution("-address-", model.Customer.Address);
            mail.Personalization[0].AddSubstitution("-groomsmen-", model.Customer.NumberOfGroomsmen.ToString());
            mail.Personalization[0].AddSubstitution("-serviceName-", model.Customer.NumberOfBridesmaids.ToString());

            client.client.mail.send.post(requestBody: mail.Get());
            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 9
0
        public void AddTo(Email email)
        {
            if (Tos == null)
                Tos = new List<Email>();

            Tos.Add(email);
        }
Ejemplo n.º 10
0
 public static async Task SendEmail(string email, string subject, string content, EmailConfig config)
 {
     dynamic sg = new SendGridAPIClient(config.SendGridApiKey);
     Email from = new Email(config.EmailFrom);
     Email to = new Email(email);
     Mail mail = new Mail(from, subject, to, new Content("text/html", content));
     dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
 }
Ejemplo n.º 11
0
 public Mail(Email from, String subject, Email to, Content content)
 {
     this.From = from;
     Personalization personalization = new Personalization();
     personalization.AddTo(to);
     this.AddPersonalization(personalization);
     this.Subject = subject;
     this.AddContent(content);
 }
        public void SendEmail(EmailModel email)
        {
            dynamic sg = new SendGridAPIClient("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");

            Email from = new Email("*****@*****.**","Brilliant Engineering Ltd");
            String subject = email.Subject;
            Email to = new Email(email.EmailAddress);
            Content content = new Content("text/html", email.Body);
            Mail mail = new Mail(from, subject, to, content);

            dynamic response = sg.client.mail.send.post(requestBody: mail.Get());
        }
Ejemplo n.º 13
0
        public ActionResult Register(CustomerModel model)
        {
            if (ModelState.IsValid)
            {
                if (WebMatrix.WebData.WebSecurity.UserExists(model.Email))
                {
                    ModelState.AddModelError("Email", "Could not create a user with this email address");
                }
                else
                {
                    string token = WebMatrix.WebData.WebSecurity.CreateUserAndAccount(model.Email, model.Password,
                                                                                      new
                    {
                        ID                  = model.ID,
                        BrideFirstName      = model.BrideFirstName,
                        BrideLastName       = model.BrideFirstName,
                        GroomFirstName      = model.GroomFirstName,
                        GroomLastName       = model.GroomFirstName,
                        Email               = model.Email,
                        PhoneNumber         = model.PhoneNumber,
                        Address             = model.Address,
                        City                = model.City,
                        WeddingDate         = model.WeddingDate,
                        NumberOfGuests      = model.NumberOfGuests,
                        NumberOfGroomsmen   = model.NumberOfGroomsmen,
                        NumberOfBridesmaids = model.NumberOfBridesmaids,
                        Password            = model.Password
                    }, true);

                    string apiKey = ConfigurationManager.AppSettings["SendGrid.Key"];
                    SendGrid.SendGridAPIClient client = new SendGrid.SendGridAPIClient(apiKey);

                    SendGrid.Helpers.Mail.Email from = new SendGrid.Helpers.Mail.Email("*****@*****.**");
                    string subject = "Couture Events Account Verification";
                    SendGrid.Helpers.Mail.Email to = new SendGrid.Helpers.Mail.Email(model.Email);
                    Content content = new Content("text/html", "emailContent");

                    string emailContent = string.Format("<html><head><body><a href=\"{0}\"Complete your registration </body></head></html>", Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/RegistrationComplete/" + HttpUtility.UrlEncode(token) + "?email=" + model.Email);
                    Mail   mail         = new Mail(from, subject, to, content);

                    client.client.mail.send.post(requestBody: mail.Get());



                    return(RedirectToAction("RegistrationComplete"));
                }
            }
            return(View(model));
        }
Ejemplo n.º 14
0
 public void SendEmail(EmailViewModel emailDetails)
 {
     string body = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Partials/Emails/AdminNotificationTemplate.html"));
     body = body.Replace("{UserName}", _toPerson);
     body = body.Replace("{EventTitle}", emailDetails.Title);
     body = body.Replace("{ShortDescription}", emailDetails.Body);
     body = body.Replace("{TodaysDate}", "" + GetNZLocalTime());
     body = body.Replace("{LongDescription}", emailDetails.Footer);
     string subject = "" + emailDetails.Subject;
     dynamic sg = new SendGridAPIClient(_emailApiKey);
     Email from = new Email(_fromEmail, _fromPerson);
     Email to = new Email(_toEmail);
     Content content = new Content("text/html", body);
     Mail mail = new Mail(from, subject, to, content);
     dynamic response = sg.client.mail.send.post(requestBody: mail.Get());
 }
Ejemplo n.º 15
0
        public async Task SendAsync(string to, string subject, string content, string contentType)
        {
            try
            {
                var sg = new SendGridAPIClient(_apiKey);

                var emailFrom    = new SendGrid.Helpers.Mail.Email(_from, "Home Chaley Bank");
                var emailTo      = new SendGrid.Helpers.Mail.Email(to);
                var emailContent = new Content(contentType, content);
                var mail         = new Mail(emailFrom, subject, emailTo, emailContent);

                await sg.client.mail.send.post(requestBody : mail.Get());
            }
            catch (Exception ex)
            {
                Logger.Error($"Can't send email to {to} about {subject}: {ex.Message}");
            }
        }
Ejemplo n.º 16
0
        private async Task SendEmailAsync(EmailMessage message)
        {
            dynamic sendGrid = new SendGridAPIClient(MailAccount);

            var from = new Email(SendAddress);
            var to = new Email(message.Destination);
            var content = new Content("text/plain", message.Body);
            var mail = new Mail(from, message.Subject, to, content);

            try
            {
                dynamic response = await sendGrid.client.mail.send.post(requestBody: mail.Get());
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message + " SendGrid probably not configured correctly.");
            }
        }
Ejemplo n.º 17
0
        private static async Task SendMailAsync(MailMessage message)
        {
            string  apiKey = ApplicationSettingsFactory.GetApplicationSettings().APIKey;
            dynamic sg     = new SendGridAPIClient(apiKey);

            SendGrid.Helpers.Mail.Email from = new SendGrid.Helpers.Mail.Email(message.From.ToString());
            SendGrid.Helpers.Mail.Email to   = new SendGrid.Helpers.Mail.Email(message.To.ToString());

            Content content;

            if (message.IsBodyHtml)
            {
                content = new Content("text/html", message.Body);
            }
            else
            {
                content = new Content("text/plain", message.Body);
            }

            Mail mail = new Mail(from, message.Subject, to, content);

            dynamic response = await sg.client.mail.send.post(requestBody : mail.Get());
        }
Ejemplo n.º 18
0
        private static async Task TemplateWithHelper()
        {
            String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
            dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

            Email from = new Email("*****@*****.**");
            String subject = "I'm replacing the subject tag";
            Email to = new Email("*****@*****.**");
            Content content = new Content("text/html", "I'm replacing the <strong>body tag</strong>");
            Mail mail = new Mail(from, subject, to, content);

            mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932";
            mail.Personalization[0].AddSubstitution("-name-", "Example User");
            mail.Personalization[0].AddSubstitution("-city-", "Denver");

            dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers.ToString());

            Console.ReadLine();

        }
Ejemplo n.º 19
0
        private static Mail FormSendGridMail(EmailMessage message)
        {
            SendGridEmail from    = new SendGridEmail(message.From);
            string        subject = message.Subject;
            Content       content = new Content(message.ContentType, message.EmailContent);
            Mail          mail    = new Mail();

            mail.From    = from;
            mail.Subject = subject;
            mail.AddContent(content);
            var tos = new List <SendGridEmail>();

            foreach (var to in message.To)
            {
                tos.Add(new SendGridEmail(to));
            }

            mail.AddPersonalization(new Personalization
            {
                Tos = tos
            });

            return(mail);
        }
Ejemplo n.º 20
0
        private static async Task KitchenSink()
        {
            String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
            dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

            Mail mail = new Mail();

            Email email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            mail.From = email;

            mail.Subject = "Hello World from the SendGrid CSharp Library";

            Personalization personalization = new Personalization();
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddTo(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            personalization.Subject = "Thank you for signing up, %name%";
            personalization.AddHeader("X-Test", "True");
            personalization.AddHeader("X-Mock", "True");
            personalization.AddSubstitution("%name%", "Example User");
            personalization.AddSubstitution("%city%", "Denver");
            personalization.AddCustomArgs("marketing", "false");
            personalization.AddCustomArgs("transactional", "true");
            personalization.SendAt = 1461775051;
            mail.AddPersonalization(personalization);

            personalization = new Personalization();
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddTo(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            personalization.Subject = "Thank you for signing up, %name%";
            personalization.AddHeader("X-Test", "True");
            personalization.AddHeader("X-Mock", "True");
            personalization.AddSubstitution("%name%", "Example User");
            personalization.AddSubstitution("%city%", "Denver");
            personalization.AddCustomArgs("marketing", "false");
            personalization.AddCustomArgs("transactional", "true");
            personalization.SendAt = 1461775051;
            mail.AddPersonalization(personalization);

            Content content = new Content();
            content.Type = "text/plain";
            content.Value = "Textual content";
            mail.AddContent(content);
            content = new Content();
            content.Type = "text/html";
            content.Value = "<html><body>HTML content</body></html>";
            mail.AddContent(content);
            content = new Content();
            content.Type = "text/calendar";
            content.Value = "Party Time!!";
            mail.AddContent(content);

            Attachment attachment = new Attachment();
            attachment.Content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12";
            attachment.Type = "application/pdf";
            attachment.Filename = "balance_001.pdf";
            attachment.Disposition = "attachment";
            attachment.ContentId = "Balance Sheet";
            mail.AddAttachment(attachment);

            attachment = new Attachment();
            attachment.Content = "BwdW";
            attachment.Type = "image/png";
            attachment.Filename = "banner.png";
            attachment.Disposition = "inline";
            attachment.ContentId = "Banner";
            mail.AddAttachment(attachment);

            mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932";

            mail.AddHeader("X-Day", "Monday");
            mail.AddHeader("X-Month", "January");

            mail.AddSection("%section1", "Substitution for Section 1 Tag");
            mail.AddSection("%section2", "Substitution for Section 2 Tag");

            mail.AddCategory("customer");
            mail.AddCategory("vip");

            mail.AddCustomArgs("campaign", "welcome");
            mail.AddCustomArgs("sequence", "2");

            ASM asm = new ASM();
            asm.GroupId = 3;
            List<int> groups_to_display = new List<int>()
            {
                1, 4, 5
            };
            asm.GroupsToDisplay = groups_to_display;
            mail.Asm = asm;

            mail.SendAt = 1461775051;

            mail.SetIpPoolId = "23";

            // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html)
            // mail.BatchId = "some_batch_id";

            MailSettings mailSettings = new MailSettings();
            BCCSettings bccSettings = new BCCSettings();
            bccSettings.Enable = true;
            bccSettings.Email = "*****@*****.**";
            mailSettings.BccSettings = bccSettings;
            BypassListManagement bypassListManagement = new BypassListManagement();
            bypassListManagement.Enable = true;
            mailSettings.BypassListManagement = bypassListManagement;
            FooterSettings footerSettings = new FooterSettings();
            footerSettings.Enable = true;
            footerSettings.Text = "Some Footer Text";
            footerSettings.Html = "<bold>Some HTML Here</bold>";
            mailSettings.FooterSettings = footerSettings;
            SandboxMode sandboxMode = new SandboxMode();
            sandboxMode.Enable = true;
            mailSettings.SandboxMode = sandboxMode;
            SpamCheck spamCheck = new SpamCheck();
            spamCheck.Enable = true;
            spamCheck.Threshold = 1;
            spamCheck.PostToUrl = "https://gotchya.example.com";
            mailSettings.SpamCheck = spamCheck;
            mail.MailSettings = mailSettings;

            TrackingSettings trackingSettings = new TrackingSettings();
            ClickTracking clickTracking = new ClickTracking();
            clickTracking.Enable = true;
            clickTracking.EnableText = false;
            trackingSettings.ClickTracking = clickTracking;
            OpenTracking openTracking = new OpenTracking();
            openTracking.Enable = true;
            openTracking.SubstitutionTag = "Optional tag to replace with the open image in the body of the message";
            trackingSettings.OpenTracking = openTracking;
            SubscriptionTracking subscriptionTracking = new SubscriptionTracking();
            subscriptionTracking.Enable = true;
            subscriptionTracking.Text = "text to insert into the text/plain portion of the message";
            subscriptionTracking.Html = "<bold>HTML to insert into the text/html portion of the message</bold>";
            subscriptionTracking.SubstitutionTag = "text to insert into the text/plain portion of the message";
            trackingSettings.SubscriptionTracking = subscriptionTracking;
            Ganalytics ganalytics = new Ganalytics();
            ganalytics.Enable = true;
            ganalytics.UtmCampaign = "some campaign";
            ganalytics.UtmContent = "some content";
            ganalytics.UtmMedium = "some medium";
            ganalytics.UtmSource = "some source";
            ganalytics.UtmTerm = "some term";
            trackingSettings.Ganalytics = ganalytics;
            mail.TrackingSettings = trackingSettings;

            email = new Email();
            email.Address = "*****@*****.**";
            mail.ReplyTo = email;

            dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers.ToString());

            Console.WriteLine(mail.Get());
            Console.ReadLine();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Sends the generated report.
        /// </summary>
        /// <param name="log">The writer for logging.</param>
        /// <param name="clubInfo">Info about the club of interest</param>
        /// <param name="subject">The email subject</param>
        /// <param name="body">The email body</param>
        /// <returns>A task that completes when the email has been sent.</returns>
        private static async Task SendDailyReportEmail(TextWriter log, ClubInfo clubInfo, string subject, string body)
        {
            dynamic sg = new SendGridAPIClient(EnvironmentDefinition.Instance.SendGridApiKey);

            Email from = new Email(clubInfo.DailyReportSender);
            Content content = new Content("text/html", body);

            string[] recipients = new string[0];

            if (EnvironmentDefinition.Instance.IsDevelopment)
            {
                recipients = new string[] { CloudConfigurationManager.GetSetting("DeveloperEmail", false) };
            }
            else if (EnvironmentDefinition.Instance.IsProduction)
            {
                recipients = clubInfo.DailyReportRecipients.Split(',');
            }

            foreach (var recipient in recipients)
            {
                try
                {
                    Email to = new Email(recipient);
                    Mail mail = new Mail(from, subject, to, content);

                    dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());

                    log.WriteLine($"Sent report email to {recipient}");
                }
                catch (Exception ex)
                {
                    log.WriteLine($"Failed to send report email to {recipient}: {ex.Message}");
                }
            }
        }
Ejemplo n.º 22
0
        private static void HelloEmail()
        {
            String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
            dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

            Email from = new Email("*****@*****.**");
            String subject = "Hello World from the SendGrid CSharp Library";
            Email to = new Email("*****@*****.**");
            Content content = new Content("text/plain", "Textual content");
            Mail mail = new Mail(from, subject, to, content);
            Email email = new Email("*****@*****.**");
            mail.Personalization[0].AddTo(email);

            String ret = mail.Get();

            string requestBody = ret;
            dynamic response = sg.client.mail.send.beta.post(requestBody: requestBody);
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers.ToString());

            Console.WriteLine(ret);
            Console.ReadLine();
        }
Ejemplo n.º 23
0
        public void TestKitchenSink()
        {
            Mail mail = new Mail();

            Email email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            mail.From = email;

            mail.Subject = "Hello World from the SendGrid CSharp Library";

            Personalization personalization = new Personalization();
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddTo(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            personalization.Subject = "Thank you for signing up, %name%";
            personalization.AddHeader("X-Test", "True");
            personalization.AddHeader("X-Mock", "True");
            personalization.AddSubstitution("%name%", "Example User");
            personalization.AddSubstitution("%city%", "Denver");
            personalization.AddCustomArgs("marketing", "false");
            personalization.AddCustomArgs("transactional", "true");
            personalization.SendAt = 1461775051;
            mail.AddPersonalization(personalization);

            personalization = new Personalization();
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddTo(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            email = new Email();
            email.Name = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            personalization.Subject = "Thank you for signing up, %name%";
            personalization.AddHeader("X-Test", "True");
            personalization.AddHeader("X-Mock", "True");
            personalization.AddSubstitution("%name%", "Example User");
            personalization.AddSubstitution("%city%", "Denver");
            personalization.AddCustomArgs("marketing", "false");
            personalization.AddCustomArgs("transactional", "true");
            personalization.SendAt = 1461775051;
            mail.AddPersonalization(personalization);

            Content content = new Content();
            content.Type = "text/plain";
            content.Value = "Textual content";
            mail.AddContent(content);
            content = new Content();
            content.Type = "text/html";
            content.Value = "<html><body>HTML content</body></html>";
            mail.AddContent(content);
            content = new Content();
            content.Type = "text/calendar";
            content.Value = "Party Time!!";
            mail.AddContent(content);

            Attachment attachment = new Attachment();
            attachment.Content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12";
            attachment.Type = "application/pdf";
            attachment.Filename = "balance_001.pdf";
            attachment.Disposition = "attachment";
            attachment.ContentId = "Balance Sheet";
            mail.AddAttachment(attachment);

            attachment = new Attachment();
            attachment.Content = "BwdW";
            attachment.Type = "image/png";
            attachment.Filename = "banner.png";
            attachment.Disposition = "inline";
            attachment.ContentId = "Banner";
            mail.AddAttachment(attachment);

            mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932";

            mail.AddHeader("X-Day", "Monday");
            mail.AddHeader("X-Month", "January");

            mail.AddSection("%section1", "Substitution for Section 1 Tag");
            mail.AddSection("%section2", "Substitution for Section 2 Tag");

            mail.AddCategory("customer");
            mail.AddCategory("vip");

            mail.AddCustomArgs("campaign", "welcome");
            mail.AddCustomArgs("sequence", "2");

            ASM asm = new ASM();
            asm.GroupId = 3;
            List<int> groups_to_display = new List<int>()
            {
                1, 4, 5
            };
            asm.GroupsToDisplay = groups_to_display;
            mail.Asm = asm;

            mail.SendAt = 1461775051;

            mail.SetIpPoolId = "23";

            // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html)
            // mail.BatchId = "some_batch_id";

            MailSettings mailSettings = new MailSettings();
            BCCSettings bccSettings = new BCCSettings();
            bccSettings.Enable = true;
            bccSettings.Email = "*****@*****.**";
            mailSettings.BccSettings = bccSettings;
            BypassListManagement bypassListManagement = new BypassListManagement();
            bypassListManagement.Enable = true;
            mailSettings.BypassListManagement = bypassListManagement;
            FooterSettings footerSettings = new FooterSettings();
            footerSettings.Enable = true;
            footerSettings.Text = "Some Footer Text";
            footerSettings.Html = "<bold>Some HTML Here</bold>";
            mailSettings.FooterSettings = footerSettings;
            SandboxMode sandboxMode = new SandboxMode();
            sandboxMode.Enable = true;
            mailSettings.SandboxMode = sandboxMode;
            SpamCheck spamCheck = new SpamCheck();
            spamCheck.Enable = true;
            spamCheck.Threshold = 1;
            spamCheck.PostToUrl = "https://gotchya.example.com";
            mailSettings.SpamCheck = spamCheck;
            mail.MailSettings = mailSettings;

            TrackingSettings trackingSettings = new TrackingSettings();
            ClickTracking clickTracking = new ClickTracking();
            clickTracking.Enable = true;
            clickTracking.EnableText = false;
            trackingSettings.ClickTracking = clickTracking;
            OpenTracking openTracking = new OpenTracking();
            openTracking.Enable = true;
            openTracking.SubstitutionTag = "Optional tag to replace with the open image in the body of the message";
            trackingSettings.OpenTracking = openTracking;
            SubscriptionTracking subscriptionTracking = new SubscriptionTracking();
            subscriptionTracking.Enable = true;
            subscriptionTracking.Text = "text to insert into the text/plain portion of the message";
            subscriptionTracking.Html = "<bold>HTML to insert into the text/html portion of the message</bold>";
            subscriptionTracking.SubstitutionTag = "text to insert into the text/plain portion of the message";
            trackingSettings.SubscriptionTracking = subscriptionTracking;
            Ganalytics ganalytics = new Ganalytics();
            ganalytics.Enable = true;
            ganalytics.UtmCampaign = "some campaign";
            ganalytics.UtmContent = "some content";
            ganalytics.UtmMedium = "some medium";
            ganalytics.UtmSource = "some source";
            ganalytics.UtmTerm = "some term";
            trackingSettings.Ganalytics = ganalytics;
            mail.TrackingSettings = trackingSettings;

            email = new Email();
            email.Address = "*****@*****.**";
            mail.ReplyTo = email;

            String ret = mail.Get();
            String final = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(ret),
                                Formatting.None,
                                new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Include });
            Assert.AreEqual(final, "{\"from\":{\"name\":\"Example User\",\"email\":\"[email protected]\"},\"subject\":\"Hello World from the SendGrid CSharp Library\",\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"cc\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"},{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"},{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"subject\":\"Thank you for signing up, %name%\",\"headers\":{\"X-Test\":\"True\",\"X-Mock\":\"True\"},\"substitutions\":{\"%name%\":\"Example User\",\"%city%\":\"Denver\"},\"custom_args\":{\"marketing\":\"false\",\"transactional\":\"true\"},\"send_at\":1461775051},{\"to\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"cc\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"},{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"[email protected]\"},{\"name\":\"Example User\",\"email\":\"[email protected]\"}],\"subject\":\"Thank you for signing up, %name%\",\"headers\":{\"X-Test\":\"True\",\"X-Mock\":\"True\"},\"substitutions\":{\"%name%\":\"Example User\",\"%city%\":\"Denver\"},\"custom_args\":{\"marketing\":\"false\",\"transactional\":\"true\"},\"send_at\":1461775051}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Textual content\"},{\"type\":\"text/html\",\"value\":\"<html><body>HTML content</body></html>\"},{\"type\":\"text/calendar\",\"value\":\"Party Time!!\"}],\"attachments\":[{\"content\":\"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12\",\"type\":\"application/pdf\",\"filename\":\"balance_001.pdf\",\"disposition\":\"attachment\",\"content_id\":\"Balance Sheet\"},{\"content\":\"BwdW\",\"type\":\"image/png\",\"filename\":\"banner.png\",\"disposition\":\"inline\",\"content_id\":\"Banner\"}],\"template_id\":\"13b8f94f-bcae-4ec6-b752-70d6cb59f932\",\"headers\":{\"X-Day\":\"Monday\",\"X-Month\":\"January\"},\"sections\":{\"%section1\":\"Substitution for Section 1 Tag\",\"%section2\":\"Substitution for Section 2 Tag\"},\"categories\":[\"customer\",\"vip\"],\"custom_args\":{\"campaign\":\"welcome\",\"sequence\":\"2\"},\"send_at\":1461775051,\"asm\":{\"group_id\":3,\"groups_to_display\":[1,4,5]},\"ip_pool_name\":\"23\",\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"[email protected]\"},\"bypass_list_management\":{\"enable\":true},\"footer\":{\"enable\":true,\"text\":\"Some Footer Text\",\"html\":\"<bold>Some HTML Here</bold>\"},\"sandbox_mode\":{\"enable\":true},\"spam_check\":{\"enable\":true,\"threshold\":1,\"post_to_url\":\"https://gotchya.example.com\"}},\"tracking_settings\":{\"click_tracking\":{\"enable\":true,\"enable_text\":false},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"Optional tag to replace with the open image in the body of the message\"},\"subscription_tracking\":{\"enable\":true,\"text\":\"text to insert into the text/plain portion of the message\",\"html\":\"<bold>HTML to insert into the text/html portion of the message</bold>\",\"substitution_tag\":\"text to insert into the text/plain portion of the message\"},\"ganalytics\":{\"enable\":true,\"utm_source\":\"some source\",\"utm_medium\":\"some medium\",\"utm_term\":\"some term\",\"utm_content\":\"some content\",\"utm_campaign\":\"some campaign\"}},\"reply_to\":{\"email\":\"[email protected]\"}}");
        }
Ejemplo n.º 24
0
        private async Task<dynamic> SendEmailConfirmation(ApplicationUser user)
        {
            //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            var callbackUrl = Url.Action("ConfirmEmail", "Account", new { token = user.Id, code = code }, protocol: Request.Url.Scheme);
            const string apiKey = "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";
            dynamic sg = new SendGridAPIClient(apiKey);

            var from = new Email("*****@*****.**");
            var subject = "Confirm your YOURSITE account";
            var to = new Email(user.Email);
            var content = new Content("text/html", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
            var mail = new Mail(from, subject, to, content);

            dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
            //await sg.client.mail.send.post(requestBody: mail.Get());
            return response;
        }