Esempio n. 1
0
        /// <summary>
        /// Create a segment.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="conditions">The conditions.</param>
        /// <param name="listId">The list identifier.</param>
        /// <param name="onBehalfOf">The user to impersonate.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// The <see cref="Segment" />.
        /// </returns>
        public Task <Segment> CreateAsync(string name, IEnumerable <SearchCondition> conditions, long?listId = null, string onBehalfOf = null, CancellationToken cancellationToken = default)
        {
            conditions = conditions ?? Enumerable.Empty <SearchCondition>();

            var data = new JObject
            {
                { "name", name },
                { "conditions", JArray.FromObject(conditions.ToArray()) }
            };

            data.AddPropertyIfValue("list_id", listId);

            return(_client
                   .PostAsync(_endpoint)
                   .OnBehalfOf(onBehalfOf)
                   .WithJsonBody(data)
                   .WithCancellationToken(cancellationToken)
                   .AsSendGridObject <Segment>());
        }
Esempio n. 2
0
        /// <summary>
        /// Create a sub account under the master account.
        /// </summary>
        /// <param name="firstName">User's first name.</param>
        /// <param name="lastName">User's last name.</param>
        /// <param name="email">User's email address.</param>
        /// <param name="password">User's password.</param>
        /// <param name="useSharedVirtualRoomConnectors">Enable/disable the option for a sub account to use shared Virtual Room Connector(s).</param>
        /// <param name="roomConnectorsIpAddresses">The IP addresses of the Room Connectors that you would like to share with the sub account.</param>
        /// <param name="useSharedMeetingConnectors">Enable/disable the option for a sub account to use shared Meeting Connector(s).</param>
        /// <param name="meetingConnectorsIpAddresses">The IP addresses of the Meeting Connectors that you would like to share with the sub account.</param>
        /// <param name="payMode">Payee.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An array of <see cref="Account">accounts</see>.
        /// </returns>
        public Task <Account> CreateAsync(string firstName, string lastName, string email, string password, bool useSharedVirtualRoomConnectors = false, IEnumerable <string> roomConnectorsIpAddresses = null, bool useSharedMeetingConnectors = false, IEnumerable <string> meetingConnectorsIpAddresses = null, PayMode payMode = PayMode.Master, CancellationToken cancellationToken = default)
        {
            var data = new JObject()
            {
                { "first_name", firstName },
                { "last_name", lastName },
                { "email", email },
                { "password", password }
            };

            data.AddPropertyIfValue("options/share_rc", useSharedVirtualRoomConnectors);
            data.AddPropertyIfValue("options/room_connectors", roomConnectorsIpAddresses, ipAddresses => JToken.Parse(string.Join(",", ipAddresses)));
            data.AddPropertyIfValue("options/share_mc", useSharedMeetingConnectors);
            data.AddPropertyIfValue("options/meeting_connectors", meetingConnectorsIpAddresses, ipAddresses => JToken.Parse(string.Join(",", ipAddresses)));
            data.AddPropertyIfValue("options/pay_mode", payMode);

            return(_client
                   .PostAsync($"accounts")
                   .WithJsonBody(data)
                   .WithCancellationToken(cancellationToken)
                   .AsObject <Account>());
        }
Esempio n. 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="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>
        /// <exception cref="Exception">Email exceeds the size limit</exception>
        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))
        {
            if (personalizations != null && personalizations.Any())
            {
                // - The total number of recipients must be less than 1000. This includes all recipients defined within the to, cc, and bcc parameters, across each object that you include in the personalizations array.
                var numberOfRecipients = personalizations.Sum(p => p?.To?.Count(r => r != null) ?? 0);
                numberOfRecipients += personalizations.Sum(p => p?.Cc?.Count(r => r != null) ?? 0);
                numberOfRecipients += personalizations.Sum(p => p?.Bcc?.Count(r => r != null) ?? 0);
                if (numberOfRecipients >= 1000)
                {
                    throw new ArgumentOutOfRangeException("The total number of recipients must be less than 1000");
                }
            }

            var data = new JObject();

            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 (personalizations != null && personalizations.Any())
            {
                // It's important to make a copy of the personalizations to ensure we don't modify the original array
                var personalizationsCopy = personalizations.ToArray();
                foreach (var personalization in personalizationsCopy)
                {
                    personalization.To  = EnsureRecipientsNamesAreQuoted(personalization.To);
                    personalization.Cc  = EnsureRecipientsNamesAreQuoted(personalization.Cc);
                    personalization.Bcc = EnsureRecipientsNamesAreQuoted(personalization.Bcc);
                }

                data.Add("personalizations", JToken.FromObject(personalizationsCopy));
            }

            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);
            }

            // Sendgrid does not allow emails that exceed 30MB
            var contentSize = JsonConvert.SerializeObject(data, Formatting.None).Length;

            if (contentSize > MAX_EMAIL_SIZE)
            {
                throw new Exception("Email exceeds the size limit");
            }

            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);
        }
Esempio n. 4
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 addresses.</param>
        /// <param name="attachments">The attachments.</param>
        /// <param name="templateId">The template identifier.</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="priority">The priority.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        /// The message id.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">Too many recipients.</exception>
        /// <exception cref="Exception">Email exceeds the size limit.</exception>
        public async Task <string> SendAsync(
            IEnumerable <MailPersonalization> personalizations,
            string subject,
            IEnumerable <MailContent> contents,
            MailAddress from,
            IEnumerable <MailAddress> replyTo    = null,
            IEnumerable <Attachment> attachments = null,
            string templateId = 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,
            MailPriority priority               = MailPriority.Normal,
            CancellationToken cancellationToken = default)
        {
            if (_client?.BaseClient?.DefaultRequestHeaders?.Authorization?.Scheme?.Equals("Basic", StringComparison.OrdinalIgnoreCase) ?? false)
            {
                const string errorMessage  = "SendGrid does not support Basic authentication when sending transactional emails.";
                const string diagnosticLog = "This request was not dispatched to SendGrid because the exception returned by their API in this scenario is not clear: 'Permission denied, wrong credentials'.";
                throw new SendGridException(errorMessage, null, diagnosticLog);
            }

            if (personalizations == null || !personalizations.Any())
            {
                throw new ArgumentNullException(nameof(personalizations));
            }

            // This comparer is used to perform case-insensitive comparisons of email addresses
            var emailAddressComparer = new LambdaComparer <MailAddress>((address1, address2) => address1.Email.Equals(address2.Email, StringComparison.OrdinalIgnoreCase));

            // It's important to make a copy of the personalizations to ensure we don't modify the original array
            var personalizationsCopy = personalizations.Where(p => p != null).ToArray();

            foreach (var personalization in personalizationsCopy)
            {
                // Make sure the arrays are not null otherwise Linq's 'Except' method will throw a ArgumentNull exception (See GH-286).
                if (personalization.To == null)
                {
                    personalization.To = Array.Empty <MailAddress>();
                }
                if (personalization.Cc == null)
                {
                    personalization.Cc = Array.Empty <MailAddress>();
                }
                if (personalization.Bcc == null)
                {
                    personalization.Bcc = Array.Empty <MailAddress>();
                }

                // Avoid duplicate addresses. This is important because SendGrid does not throw any
                // exception when a recipient is duplicated (which gives you the impression the email
                // was sent) but it does not actually send the email
                personalization.To = personalization.To
                                     .Distinct(emailAddressComparer)
                                     .ToArray();
                personalization.Cc = personalization.Cc
                                     .Distinct(emailAddressComparer)
                                     .Except(personalization.To, emailAddressComparer)
                                     .ToArray();
                personalization.Bcc = personalization.Bcc
                                      .Distinct(emailAddressComparer)
                                      .Except(personalization.To, emailAddressComparer)
                                      .Except(personalization.Cc, emailAddressComparer)
                                      .ToArray();

                // SendGrid doesn't like empty arrays
                if (!personalization.To.Any())
                {
                    personalization.To = null;
                }
                if (!personalization.Cc.Any())
                {
                    personalization.Cc = null;
                }
                if (!personalization.Bcc.Any())
                {
                    personalization.Bcc = null;
                }

                // Surround recipient names with double-quotes if necessary
                personalization.To  = EnsureRecipientsNamesAreQuoted(personalization.To);
                personalization.Cc  = EnsureRecipientsNamesAreQuoted(personalization.Cc);
                personalization.Bcc = EnsureRecipientsNamesAreQuoted(personalization.Bcc);

                // Indicate if a dynamic template is being used. This is used by MailPersonalizationConverter to generate the appropriate JSON
                personalization.IsUsedWithDynamicTemplate = Template.IsDynamic(templateId);
            }

            // The total number of recipients must be less than 1000. This includes all recipients defined within the to, cc, and bcc parameters, across each object that you include in the personalizations array.
            var numberOfRecipients = personalizationsCopy.Sum(p => p.To?.Count(r => r != null) ?? 0);

            numberOfRecipients += personalizationsCopy.Sum(p => p.Cc?.Count(r => r != null) ?? 0);
            numberOfRecipients += personalizationsCopy.Sum(p => p.Bcc?.Count(r => r != null) ?? 0);
            if (numberOfRecipients >= 1000)
            {
                throw new ArgumentOutOfRangeException(nameof(numberOfRecipients), numberOfRecipients, "The total number of recipients must be less than 1000");
            }

            // Get the priority headers
            if (!_priorityHeaders.TryGetValue(priority, out KeyValuePair <string, string>[] priorityHeaders))
            {
                throw new Exception($"{priority} is an unknown priority");
            }

            // Combine headers with priority headers making sure not to duplicate priority headers
            var combinedHeaders = (headers ?? Array.Empty <KeyValuePair <string, string> >())
                                  .Where(kvp => !priorityHeaders.Any(p => p.Key.Equals(kvp.Key, StringComparison.OrdinalIgnoreCase)))
                                  .Concat(priorityHeaders);

            // Remove duplicates from the list of 'reply-to' addresses
            var cleanReplyTo = replyTo?.Distinct(emailAddressComparer) ?? Enumerable.Empty <MailAddress>();

            // SendGrid allows no more than 1000 'reply-to' addresses
            var numberOfReplyToAddresses = cleanReplyTo.Count();

            if (numberOfReplyToAddresses > 1000)
            {
                throw new ArgumentOutOfRangeException(nameof(numberOfReplyToAddresses), numberOfReplyToAddresses, "The number of distinct reply-to addresses can't exceed 1000");
            }

            // Serialize the mail message
            var data = new StrongGridJsonObject();

            data.AddProperty("from", from);
            data.AddProperty("reply_to_list", cleanReplyTo);
            data.AddProperty("subject", subject);
            data.AddProperty("content", contents);
            data.AddProperty("attachments", attachments);
            data.AddProperty("template_id", templateId);
            data.AddProperty("categories", categories);
            data.AddProperty("send_at", sendAt?.ToUnixTime());
            data.AddProperty("batch_id", batchId);
            data.AddProperty("asm", unsubscribeOptions);
            data.AddProperty("ip_pool_name", ipPoolName);
            data.AddProperty("mail_settings", mailSettings);
            data.AddProperty("tracking_settings", trackingSettings);
            data.AddProperty("personalizations", personalizationsCopy);
            data.AddProperty("headers", ConvertEnumerationToJson(combinedHeaders));
            data.AddProperty("custom_args", ConvertEnumerationToJson(customArgs));

            // SendGrid does not allow emails that exceed 30MB
            var serializedContent = JsonSerializer.Serialize(data, typeof(StrongGridJsonObject), JsonFormatter.SerializationContext);

            if (serializedContent.Length > MAX_EMAIL_SIZE)
            {
                throw new Exception("Email exceeds the size limit");
            }

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

            // Get the messageId from the response
            return(response.Message.Headers.GetValue("X-Message-Id"));
        }
Esempio n. 5
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>
        /// <exception cref="ArgumentOutOfRangeException">Too many recipients.</exception>
        /// <exception cref="Exception">Email exceeds the size limit.</exception>
        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)
        {
            if (personalizations == null || !personalizations.Any())
            {
                throw new ArgumentNullException(nameof(personalizations));
            }

            // This comparer is used to perform case-insensitive comparisons of email addresses
            var emailAddressComparer = new LambdaComparer <MailAddress>((address1, address2) => address1.Email.Equals(address2.Email, StringComparison.OrdinalIgnoreCase));

            // It's important to make a copy of the personalizations to ensure we don't modify the original array
            var personalizationsCopy = personalizations.Where(p => p != null).ToArray();

            foreach (var personalization in personalizationsCopy)
            {
                // Avoid duplicate addresses. This is important because SendGrid does not throw any
                // exception when a recipient is duplicated (which gives you the impression the email
                // was sent) but it does not actually send the email
                personalization.To = personalization.To?
                                     .Distinct(emailAddressComparer)
                                     .ToArray();
                personalization.Cc = personalization.Cc?
                                     .Distinct(emailAddressComparer)
                                     .Except(personalization.To, emailAddressComparer)
                                     .ToArray();
                personalization.Bcc = personalization.Bcc?
                                      .Distinct(emailAddressComparer)
                                      .Except(personalization.To, emailAddressComparer)
                                      .Except(personalization.Cc, emailAddressComparer)
                                      .ToArray();

                // SendGrid doesn't like empty arrays
                if (!(personalization.To?.Any() ?? true))
                {
                    personalization.To = null;
                }
                if (!(personalization.Cc?.Any() ?? true))
                {
                    personalization.Cc = null;
                }
                if (!(personalization.Bcc?.Any() ?? true))
                {
                    personalization.Bcc = null;
                }

                // Surround recipient names with double-quotes if necessary
                personalization.To  = EnsureRecipientsNamesAreQuoted(personalization.To);
                personalization.Cc  = EnsureRecipientsNamesAreQuoted(personalization.Cc);
                personalization.Bcc = EnsureRecipientsNamesAreQuoted(personalization.Bcc);
            }

            // The total number of recipients must be less than 1000. This includes all recipients defined within the to, cc, and bcc parameters, across each object that you include in the personalizations array.
            var numberOfRecipients = personalizationsCopy.Sum(p => p.To?.Count(r => r != null) ?? 0);

            numberOfRecipients += personalizationsCopy.Sum(p => p.Cc?.Count(r => r != null) ?? 0);
            numberOfRecipients += personalizationsCopy.Sum(p => p.Bcc?.Count(r => r != null) ?? 0);
            if (numberOfRecipients >= 1000)
            {
                throw new ArgumentOutOfRangeException("The total number of recipients must be less than 1000");
            }

            // SendGrid throws an unhelpful error when the Bcc email address is an empty string
            if (mailSettings?.Bcc != null && string.IsNullOrWhiteSpace(mailSettings.Bcc.EmailAddress))
            {
                mailSettings.Bcc.EmailAddress = null;
            }

            var isDynamicTemplate        = Template.IsDynamic(templateId);
            var personalizationConverter = new MailPersonalizationConverter(isDynamicTemplate);

            var data = new JObject();

            data.AddPropertyIfValue("from", from);
            data.AddPropertyIfValue("reply_to", replyTo);
            data.AddPropertyIfValue("subject", subject);
            data.AddPropertyIfValue("content", contents);
            data.AddPropertyIfValue("attachments", attachments);
            data.AddPropertyIfValue("template_id", templateId);
            data.AddPropertyIfValue("categories", categories);
            data.AddPropertyIfValue("send_at", sendAt?.ToUnixTime());
            data.AddPropertyIfValue("batch_id", batchId);
            data.AddPropertyIfValue("asm", unsubscribeOptions);
            data.AddPropertyIfValue("ip_pool_name", ipPoolName);
            data.AddPropertyIfValue("mail_settings", mailSettings);
            data.AddPropertyIfValue("tracking_settings", trackingSettings);
            data.AddPropertyIfValue("personalizations", personalizationsCopy, personalizationConverter);

            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);
            }

            // Sendgrid does not allow emails that exceed 30MB
            var contentSize = JsonConvert.SerializeObject(data, Formatting.None).Length;

            if (contentSize > MAX_EMAIL_SIZE)
            {
                throw new Exception("Email exceeds the size limit");
            }

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

            if (response.Message.Headers.TryGetValues("X-Message-Id", out IEnumerable <string> values))
            {
                return(values?.FirstOrDefault());
            }

            return(null);
        }
Esempio n. 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);
        }