Example #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Tracker"/> class.
        /// </summary>
        /// <param name="settings">Settings to be used by the tracker.</param>
        /// <param name="trackingService">The tracking service client to be used to communicate
        /// with the tracking server.</param>
        /// <param name="synchronizationService">The synchronization service to be used for
        /// synchronizing data in the project and at the tracking service.</param>
        /// <param name="solver">The VRP solver to be used by the tracker.</param>
        /// <param name="geocoder">The geocoder to be used by the tracker.</param>
        /// <param name="messageReporter">The message reporter to be used for reporting
        /// tracking errors.</param>
        /// <exception cref="ArgumentNullException"><paramref name="settings"/>,
        /// <paramref name="trackingService"/>, <paramref name="synchronizationService"/>,
        /// <paramref name="solver"/>, <paramref name="geocoder"/> or
        /// <paramref name="messageReporter"/> is a null reference.</exception>
        internal Tracker(
            TrackingSettings settings,
            ITrackingService trackingService,
            ISynchronizationService synchronizationService,
            IVrpSolver solver,
            IGeocoder geocoder,
            IMessageReporter messageReporter)
        {
            CodeContract.RequiresNotNull("settings", settings);
            CodeContract.RequiresNotNull("trackingService", trackingService);
            CodeContract.RequiresNotNull("synchronizationService", synchronizationService);
            CodeContract.RequiresNotNull("solver", solver);
            CodeContract.RequiresNotNull("geocoder", geocoder);
            CodeContract.RequiresNotNull("messageReporter", messageReporter);

            _settings = settings;
            _trackingService = trackingService;
            _synchronizationService = synchronizationService;

            _solver = solver;

            _geocoder = geocoder;
            _messageReporter = messageReporter;
        }
Example #2
0
        /// <summary>
        /// Send the same email to multiple recipients using a legacy template.
        /// </summary>
        /// <param name="recipients">The recipients.</param>
        /// <param name="from">From.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="htmlContent">Content of the HTML.</param>
        /// <param name="textContent">Content of the text.</param>
        /// <param name="templateId">The template identifier.</param>
        /// <param name="substitutions">Data to be merged in the content.</param>
        /// <param name="trackOpens">if set to <c>true</c> [track opens].</param>
        /// <param name="trackClicks">if set to <c>true</c> [track clicks].</param>
        /// <param name="subscriptionTracking">The subscription tracking.</param>
        /// <param name="replyTo">The reply to.</param>
        /// <param name="attachments">The attachments.</param>
        /// <param name="sections">The sections.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="categories">The categories.</param>
        /// <param name="customArgs">The custom arguments.</param>
        /// <param name="sendAt">The send at.</param>
        /// <param name="batchId">The batch identifier.</param>
        /// <param name="unsubscribeOptions">The unsubscribe options.</param>
        /// <param name="mailSettings">The mail settings.</param>
        /// <param name="priority">The priority.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The result.
        /// </returns>
        /// <remarks>
        /// This is a convenience method with simplified parameters.
        /// If you need more options, use the <see cref="SendAsync" /> method.
        /// </remarks>
        /// <exception cref="ArgumentOutOfRangeException">Too many recipients.</exception>
        /// <exception cref="Exception">Email exceeds the size limit.</exception>
        public Task <WarmupResult> SendToMultipleRecipientsAsync(
            IEnumerable <MailAddress> recipients,
            MailAddress from,
            string subject,
            string htmlContent,
            string textContent,
            string templateId,
            IEnumerable <KeyValuePair <string, string> > substitutions = null,
            bool trackOpens  = true,
            bool trackClicks = true,
            SubscriptionTrackingSettings subscriptionTracking = null,
            MailAddress replyTo = null,
            IEnumerable <Attachment> attachments = null,
            IEnumerable <KeyValuePair <string, string> > sections = null,
            IEnumerable <KeyValuePair <string, string> > headers  = null,
            IEnumerable <string> categories = null,
            IEnumerable <KeyValuePair <string, string> > customArgs = null,
            DateTime?sendAt = null,
            string batchId  = null,
            UnsubscribeOptions unsubscribeOptions = null,
            MailSettings mailSettings             = null,
            MailPriority priority = MailPriority.Normal,
            CancellationToken cancellationToken = default)
        {
            var personalizations = new[]
            {
                new MailPersonalization
                {
                    To            = recipients.ToArray(),
                    Substitutions = substitutions?.ToArray()
                }
            };

            var contents = new List <MailContent>();

            if (!string.IsNullOrEmpty(textContent))
            {
                contents.Add(new MailContent("text/plain", textContent));
            }
            if (!string.IsNullOrEmpty(htmlContent))
            {
                contents.Add(new MailContent("text/html", htmlContent));
            }

            var trackingSettings = new TrackingSettings
            {
                ClickTracking = new ClickTrackingSettings
                {
                    EnabledInHtmlContent = trackClicks,
                    EnabledInTextContent = trackClicks
                },
                OpenTracking = new OpenTrackingSettings {
                    Enabled = trackOpens
                },
                GoogleAnalytics = new GoogleAnalyticsSettings {
                    Enabled = false
                },
                SubscriptionTracking = subscriptionTracking
            };

            return(SendAsync(personalizations, subject, contents, from, replyTo, attachments, templateId, sections, headers, categories, customArgs, sendAt, batchId, unsubscribeOptions, mailSettings, trackingSettings, priority, cancellationToken));
        }
Example #3
0
        /// <summary>
        /// Send email(s) over SendGrid’s v3 Web API.
        /// </summary>
        /// <param name="personalizations">The personalizations.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="contents">The contents.</param>
        /// <param name="from">From.</param>
        /// <param name="replyTo">The reply to.</param>
        /// <param name="attachments">The attachments.</param>
        /// <param name="templateId">The template identifier.</param>
        /// <param name="sections">The sections.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="categories">The categories.</param>
        /// <param name="customArgs">The custom arguments.</param>
        /// <param name="sendAt">The send at.</param>
        /// <param name="batchId">The batch identifier.</param>
        /// <param name="unsubscribeOptions">The unsubscribe options.</param>
        /// <param name="mailSettings">The mail settings.</param>
        /// <param name="trackingSettings">The tracking settings.</param>
        /// <param name="priority">The priority.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        /// The result.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">Too many recipients.</exception>
        /// <exception cref="Exception">Email exceeds the size limit.</exception>
        public async Task <WarmupResult> SendAsync(
            IEnumerable <MailPersonalization> personalizations,
            string subject,
            IEnumerable <MailContent> contents,
            MailAddress from,
            MailAddress replyTo = null,
            IEnumerable <Attachment> attachments = null,
            string templateId = null,
            IEnumerable <KeyValuePair <string, string> > sections = null,
            IEnumerable <KeyValuePair <string, string> > headers  = null,
            IEnumerable <string> categories = null,
            IEnumerable <KeyValuePair <string, string> > customArgs = null,
            DateTime?sendAt = null,
            string batchId  = null,
            UnsubscribeOptions unsubscribeOptions = null,
            MailSettings mailSettings             = null,
            TrackingSettings trackingSettings     = null,
            MailPriority priority = MailPriority.Normal,
            CancellationToken cancellationToken = default)
        {
            // Validate parameters
            if (personalizations == null || !personalizations.Any())
            {
                throw new ArgumentNullException(nameof(personalizations));
            }

            // Get the current warmup status
            var warmupStatus = await _warmupProgressRepository.GetWarmupStatusAsync(_warmupSettings.PoolName, cancellationToken).ConfigureAwait(false);

            var numberOfIpAddressesInThePool = warmupStatus.IpAddresses.Length;

            // Determine how many emails can be sent on the pool today
            var warmupDay         = 1;
            var emailsSentLastDay = 0;

            if (warmupStatus.DateLastSent.Date != DateTime.MinValue.Date)
            {
                if (warmupStatus.Completed)
                {
                    // The warmup process has already been completed
                    warmupDay         = 0;
                    emailsSentLastDay = 0;
                }
                else if (warmupStatus.DateLastSent.Date == _systemClock.UtcNow.Date)
                {
                    // The lastSendDate is "Today".
                    warmupDay         = warmupStatus.WarmupDay;
                    emailsSentLastDay = warmupStatus.EmailsSentLastDay;
                }
                else if (warmupStatus.DateLastSent.Date.AddDays(_warmupSettings.ResetDays) >= _systemClock.UtcNow.Date)
                {
                    // The lastSendDate is "Yesterday".
                    // Move on to the next warmupDay's sending volume.
                    warmupDay         = warmupStatus.WarmupDay + 1;
                    emailsSentLastDay = 0;
                }
                else
                {
                    // The lastSendDate is not "Yesterday". The previous warmupDay's sending volume will be repeated
                    // to avoid over-sending (this is days of warmup, not calendar days, which matters to ISPs)
                    warmupDay         = warmupStatus.WarmupDay;
                    emailsSentLastDay = 0;
                }
            }

            // Check if the process is completed
            var warmupCompleted = warmupStatus.Completed || warmupDay > _warmupSettings.DailyVolumePerIpAddress.Length;

            // Calculate the number of remaining emails for today
            var maxDailyVolume       = warmupCompleted ? 0 : numberOfIpAddressesInThePool * _warmupSettings.DailyVolumePerIpAddress[warmupDay - 1];
            var remainingDailyEmails = Math.Max(maxDailyVolume - emailsSentLastDay, 0);

            // Determine which emails will be sent from the pool and which ones will not
            var total = 0;
            var personalizationsWithRunningTotals =
                (from p in personalizations
                 select new
            {
                RunningTotal = total +=
                    p.To?.Count(r => r != null) ?? 0 +
                    p.Cc?.Count(r => r != null) ?? 0 +
                    p.Bcc?.Count(r => r != null) ?? 0,
                Personalization = p
            }).ToArray();
            var personalizationsOnPool = personalizationsWithRunningTotals
                                         .Where(p => p.RunningTotal <= remainingDailyEmails)
                                         .Select(p => p.Personalization)
                                         .ToArray();
            var personalizationsNotOnPool = personalizationsWithRunningTotals
                                            .Where(p => p.RunningTotal > remainingDailyEmails)
                                            .Select(p => p.Personalization)
                                            .ToArray();

            var emailsToSend = personalizationsOnPool
                               .Sum(p =>
                                    p.To?.Count(r => r != null) ?? 0 +
                                    p.Cc?.Count(r => r != null) ?? 0 +
                                    p.Bcc?.Count(r => r != null) ?? 0);

            // The proces could also be completed if we are on the last day of the process and there won't be any emails left to send after this batch
            warmupCompleted |= warmupDay == _warmupSettings.DailyVolumePerIpAddress.Length && remainingDailyEmails - emailsToSend <= 0;

            // Send the emails
            var tasks = new Task <string>[]
            {
                // These emails (if any) will be sent on the pool
                SendEmailAsync(
                    personalizationsOnPool,
                    subject,
                    contents,
                    from,
                    replyTo,
                    attachments,
                    templateId,
                    sections,
                    headers,
                    categories,
                    customArgs,
                    sendAt,
                    batchId,
                    unsubscribeOptions,
                    _warmupSettings.PoolName,
                    mailSettings,
                    trackingSettings,
                    priority,
                    cancellationToken),

                // These emails (if any) will not be sent on the pool
                SendEmailAsync(
                    personalizationsNotOnPool,
                    subject,
                    contents,
                    from,
                    replyTo,
                    attachments,
                    templateId,
                    sections,
                    headers,
                    categories,
                    customArgs,
                    sendAt,
                    batchId,
                    unsubscribeOptions,
                    null,
                    mailSettings,
                    trackingSettings,
                    priority,
                    cancellationToken)
            };
            await Task.WhenAll(tasks).ConfigureAwait(false);

            // Update status and clean up if necesary
            if (!warmupStatus.Completed)
            {
                // Delete the pool if the process is completed
                if (warmupCompleted)
                {
                    await _client.IpPools.DeleteAsync(_warmupSettings.PoolName, cancellationToken).ConfigureAwait(false);
                }

                // Update the progress info
                warmupStatus.Completed         = warmupCompleted;
                warmupStatus.DateLastSent      = _systemClock.UtcNow;
                warmupStatus.EmailsSentLastDay = emailsSentLastDay + emailsToSend;
                warmupStatus.WarmupDay         = warmupDay;

                await _warmupProgressRepository.UpdateStatusAsync(warmupStatus, cancellationToken);
            }

            // Return status
            return(new WarmupResult(warmupCompleted, tasks[0].Result, tasks[1].Result));
        }
Example #4
0
        private static void Mail(IClient client, bool pauseAfterTests)
        {
            Console.WriteLine("\n***** MAIL *****");

            var from             = new MailAddress("*****@*****.**", "John Smith");
            var to1              = new MailAddress("*****@*****.**", "Recipient1");
            var to2              = new MailAddress("*****@*****.**", "Recipient2");
            var subject          = "Dear {{customer_type}}";
            var textContent      = new MailContent("text/plain", "Hello world!");
            var htmlContent      = new MailContent("text/html", "<html><body>Hello <b><i>{{first_name}}!</i></b><br/></body></html>");
            var personalizations = new[]
            {
                new MailPersonalization
                {
                    To            = new[] { to1 },
                    Substitutions = new KeyValuePair <string, string>[]
                    {
                        new  KeyValuePair <string, string>("{{customer_type}}", "friend"),
                        new  KeyValuePair <string, string>("{{first_name}}", "Bob")
                    },
                    CustomArguments = new KeyValuePair <string, string>[]
                    {
                        new  KeyValuePair <string, string>("some_value_specific_to_this_person", "ABC_123")
                    }
                },
                new MailPersonalization
                {
                    To            = new[] { to2 },
                    Substitutions = new KeyValuePair <string, string>[]
                    {
                        new  KeyValuePair <string, string>("{{customer_type}}", "customer"),
                        new  KeyValuePair <string, string>("{{first_name}}", "John")
                    },
                    CustomArguments = new KeyValuePair <string, string>[]
                    {
                        new  KeyValuePair <string, string>("some_value_specific_to_this_person", "ZZZ_999")
                    }
                }
            };
            var mailSettings = new MailSettings
            {
                SandboxMode = new SandboxModeSettings
                {
                    Enabled = true
                },
                Bcc = new BccSettings
                {
                    Enabled      = true,
                    EmailAddress = "*****@*****.**"
                },
                BypassListManagement = new BypassListManagementSettings
                {
                    Enabled = false
                },
                SpamChecking = new SpamCheckingSettings
                {
                    Enabled   = false,
                    Threshold = 1,
                    PostToUrl = "http://whatever.com"
                },
                Footer = new FooterSettings
                {
                    Enabled     = true,
                    HtmlContent = "<p>This email was sent with the help of the <b><a href=\"https://www.nuget.org/packages/StrongGrid/\">StrongGrid</a></b> library</p>",
                    TextContent = "This email was sent with the help of the StrongGrid library"
                }
            };
            var trackingSettings = new TrackingSettings
            {
                ClickTracking = new ClickTrackingSettings
                {
                    EnabledInHtmlContent = true,
                    EnabledInTextContent = true
                },
                OpenTracking = new OpenTrackingSettings {
                    Enabled = true
                },
                GoogleAnalytics = new GoogleAnalyticsSettings {
                    Enabled = false
                },
                SubscriptionTracking = new SubscriptionTrackingSettings {
                    Enabled = false
                }
            };
            var headers = new KeyValuePair <string, string>[]
            {
                new  KeyValuePair <string, string>("customerId", "1234"),
            };
            var customArgs = new KeyValuePair <string, string>[]
            {
                new  KeyValuePair <string, string>("sent_on", DateTime.UtcNow.ToString("yyyy-MM-dd HH-mm-ss")),
                new  KeyValuePair <string, string>("some_other_value", "QWERTY")
            };

            var messageId = client.Mail.SendAsync(personalizations, subject, new[] { textContent, htmlContent }, from,
                                                  headers: headers,
                                                  customArgs: customArgs,
                                                  mailSettings: mailSettings,
                                                  trackingSettings: trackingSettings
                                                  ).Result;

            Console.WriteLine("Email has been sent. Message Id: {0}", messageId);

            /******
            *       Here's the simplified way to send a single email to a single recipient:
            *       var messageId = await client.Mail.SendToSingleRecipientAsync(to, from, subject, htmlContent, textContent).ConfigureAwait(false);
            *
            *       Here's the simplified way to send the same email to multiple recipients:
            *       var messageId = await client.Mail.SendToMultipleRecipientsAsync(new[] { to1, to2, to3 }, from, subject, htmlContent, textContent).ConfigureAwait(false);
            ******/

            ConcludeTests(pauseAfterTests);
        }
Example #5
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();
        }
Example #6
0
        /// <summary>
        /// Send email(s) over SendGrid’s v3 Web API
        /// </summary>
        /// <param name="personalizations">The personalizations.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="contents">The contents.</param>
        /// <param name="from">From.</param>
        /// <param name="replyTo">The reply to.</param>
        /// <param name="attachments">The attachments.</param>
        /// <param name="templateId">The template identifier.</param>
        /// <param name="sections">The sections.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="categories">The categories.</param>
        /// <param name="customArgs">The custom arguments.</param>
        /// <param name="sendAt">The send at.</param>
        /// <param name="batchId">The batch identifier.</param>
        /// <param name="unsubscribeOptions">The unsubscribe options.</param>
        /// <param name="ipPoolName">Name of the ip pool.</param>
        /// <param name="mailSettings">The mail settings.</param>
        /// <param name="trackingSettings">The tracking settings.</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>
        /// The message id.
        /// </returns>
        public async Task <string> SendAsync(
            IEnumerable <MailPersonalization> personalizations,
            string subject,
            IEnumerable <MailContent> contents,
            MailAddress from,
            MailAddress replyTo = null,
            IEnumerable <Attachment> attachments = null,
            string templateId = null,
            IEnumerable <KeyValuePair <string, string> > sections = null,
            IEnumerable <KeyValuePair <string, string> > headers  = null,
            IEnumerable <string> categories = null,
            IEnumerable <KeyValuePair <string, string> > customArgs = null,
            DateTime?sendAt = null,
            string batchId  = null,
            UnsubscribeOptions unsubscribeOptions = null,
            string ipPoolName                   = null,
            MailSettings mailSettings           = null,
            TrackingSettings trackingSettings   = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var data = new JObject();

            if (personalizations != null && personalizations.Any())
            {
                data.Add("personalizations", JToken.FromObject(personalizations.ToArray()));
            }
            if (from != null)
            {
                data.Add("from", JToken.FromObject(from));
            }
            if (replyTo != null)
            {
                data.Add("reply_to", JToken.FromObject(replyTo));
            }
            if (!string.IsNullOrEmpty(subject))
            {
                data.Add("subject", subject);
            }
            if (contents != null && contents.Any())
            {
                data.Add("content", JToken.FromObject(contents.ToArray()));
            }
            if (attachments != null && attachments.Any())
            {
                data.Add("attachments", JToken.FromObject(attachments.ToArray()));
            }
            if (!string.IsNullOrEmpty(templateId))
            {
                data.Add("template_id", templateId);
            }
            if (categories != null && categories.Any())
            {
                data.Add("categories", JToken.FromObject(categories.ToArray()));
            }
            if (sendAt.HasValue)
            {
                data.Add("send_at", sendAt.Value.ToUnixTime());
            }
            if (!string.IsNullOrEmpty(batchId))
            {
                data.Add("batch_id", batchId);
            }
            if (unsubscribeOptions != null)
            {
                data.Add("asm", JToken.FromObject(unsubscribeOptions));
            }
            if (!string.IsNullOrEmpty(ipPoolName))
            {
                data.Add("ip_pool_name", ipPoolName);
            }
            if (mailSettings != null)
            {
                data.Add("mail_settings", JToken.FromObject(mailSettings));
            }
            if (trackingSettings != null)
            {
                data.Add("tracking_settings", JToken.FromObject(trackingSettings));
            }

            if (sections != null && sections.Any())
            {
                var sctns = new JObject();
                foreach (var section in sections)
                {
                    sctns.Add(section.Key, section.Value);
                }

                data.Add("sections", sctns);
            }

            if (headers != null && headers.Any())
            {
                var hdrs = new JObject();
                foreach (var header in headers)
                {
                    hdrs.Add(header.Key, header.Value);
                }

                data.Add("headers", hdrs);
            }

            if (customArgs != null && customArgs.Any())
            {
                var args = new JObject();
                foreach (var customArg in customArgs)
                {
                    args.Add(customArg.Key, customArg.Value);
                }

                data.Add("custom_args", args);
            }

            var response = await _client
                           .PostAsync($"{_endpoint}/send")
                           .WithJsonBody(data)
                           .WithCancellationToken(cancellationToken)
                           .AsResponse()
                           .ConfigureAwait(false);

            var messageId = (string)null;

            if (response.Message.Headers.Contains("X-Message-Id"))
            {
                messageId = response.Message.Headers.GetValues("X-Message-Id").FirstOrDefault();
            }

            return(messageId);
        }
        /// <summary>
        /// Returns a reference to the <see cref="Tracker"/> class object.
        /// </summary>
        /// <param name="solver">The solver to be used by the returned tracker.</param>
        /// <param name="geocoder">The geocoder to be used by the returned tracker.</param>
        /// <param name="messageReporter">The messageReporter to be used by the returned
        /// tracker.</param>
        /// <returns>A new <see cref="Tracker"/> class instance.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="solver"/>,
        /// <paramref name="geocoder"/> or <paramref name="messageReporter"/> is a null
        /// reference.</exception>
        public Tracker GetTracker(
            IVrpSolver solver,
            IGeocoder geocoder,
            IMessageReporter messageReporter)
        {
            CodeContract.RequiresNotNull("solver", solver);
            CodeContract.RequiresNotNull("geocoder", geocoder);
            CodeContract.RequiresNotNull("messageReporter", messageReporter);

            _CheckSettings(_settings);

            var settings = new TrackingSettings
            {
                BreakTolerance = _settings.TrackingSettings.BreakTolerance ?? 0,
            };

            var uri = new Uri(_settings.TrackingServiceInfo.RestUrl);
            var service = FeatureService.Create(uri, Server);
            var trackingServiceClient = new TrackingServiceClient(service);

            var trackingService = new TrackingServiceClient(service);
            var synchronizationService = new SynchronizationService(trackingServiceClient);

            return new Tracker(
                settings,
                trackingService,
                synchronizationService,
                solver,
                geocoder,
                messageReporter);
        }
Example #8
0
        public SendGridResult SendEmail(string senderName, string senderAddress, IEnumerable <Cake.Email.Common.MailAddress> recipients, string subject, string htmlContent, string textContent, IEnumerable <Cake.Email.Common.Attachment> attachments, SendGridSettings settings)
        {
            try
            {
                if (settings == null)
                {
                    throw new ArgumentNullException(nameof(settings));
                }

                if (string.IsNullOrWhiteSpace(senderAddress))
                {
                    throw new ArgumentNullException(nameof(senderAddress), "You must specify the 'from' email address.");
                }

                if (string.IsNullOrWhiteSpace(subject))
                {
                    throw new ArgumentNullException(nameof(subject), "You must specify the subject.");
                }

                if (string.IsNullOrWhiteSpace(htmlContent) && string.IsNullOrEmpty(textContent))
                {
                    throw new ArgumentException("You must specify the HTML content and/or the text content. We can't send an empty email.");
                }

                if (recipients == null || !recipients.Any(r => r != null))
                {
                    throw new CakeException("You must specify at least one recipient");
                }

                var safeRecipients = recipients.Where(r => r != null && !string.IsNullOrEmpty(r.Address));
                if (!safeRecipients.Any())
                {
                    throw new CakeException("None of the recipients you specified have an email address");
                }

                if (attachments == null)
                {
                    attachments = Enumerable.Empty <Cake.Email.Common.Attachment>();
                }

                using (var client = new Client(settings.ApiKey))
                {
                    _context.Log.Verbose("Sending email to {0} via the SendGrid API...", string.Join(", ", safeRecipients.Select(r => r.Address).ToArray()));

                    var from             = new StrongGrid.Models.MailAddress(senderAddress, senderName);
                    var personalizations = safeRecipients.Select(r => new MailPersonalization {
                        To = new[] { new StrongGrid.Models.MailAddress(r.Address, r.Name) }
                    }).ToArray();
                    var contents = new[]
                    {
                        new MailContent("text/plain", textContent),
                        new MailContent("text/html", htmlContent),
                    };
                    var trackingSettings = new TrackingSettings
                    {
                        ClickTracking = new ClickTrackingSettings
                        {
                            EnabledInHtmlContent = false,
                            EnabledInTextContent = false,
                        },
                        OpenTracking = new OpenTrackingSettings {
                            Enabled = false
                        },
                        GoogleAnalytics = new GoogleAnalyticsSettings {
                            Enabled = false
                        },
                        SubscriptionTracking = null,
                    };

                    var sendGridAttachments = attachments
                                              .Select(a =>
                    {
                        var buffer = (byte[])null;
                        using (var ms = new MemoryStream())
                        {
                            a.ContentStream.CopyTo(ms);
                            buffer = ms.ToArray();
                        }

                        return(new StrongGrid.Models.Attachment()
                        {
                            Content = Convert.ToBase64String(buffer),
                            ContentId = a.ContentId,
                            Disposition = string.IsNullOrEmpty(a.ContentId) ? "attachment" : "inline",
                            FileName = a.Name,
                            Type = a.MimeType,
                        });
                    }).ToArray();

                    var messageId = client.Mail.SendAsync(personalizations, subject, contents, from, null, sendGridAttachments, null, null, null, null, null, null, null, null, null, null, trackingSettings).Result;
                    return(new SendGridResult(true, messageId, DateTime.UtcNow.ToString("u"), string.Empty));
                }
            }
            catch (Exception e)
            {
                while (e.InnerException != null)
                {
                    e = e.InnerException;
                }

                if (settings.ThrowOnFail.HasValue && settings.ThrowOnFail.Value)
                {
                    throw new CakeException(e.Message);
                }
                else
                {
                    return(new SendGridResult(false, null, DateTime.UtcNow.ToString("u"), e.Message));
                }
            }
        }