/// <summary>
        ///     Delivers the message asynchronous.
        /// </summary>
        /// <param name="deliveryItem">The delivery item.</param>
        /// <param name="autoCloseConnection">
        ///     If set to <c>true</c> will close connection immediately after delivering the message.
        ///     If caller is sending multiple messages, optionally set to false to leave the mail service connection open.
        /// </param>
        /// <param name="token">The cancellation token.</param>
        /// <returns>System.Threading.Tasks.Task&lt;System.String&gt;.</returns>
        /// <exception cref="System.Exception"></exception>
        /// <remarks>The implementor should return a provider specific ID value.</remarks>
        protected override async Task <string> DeliverMessageAsync(
            DeliveryItem deliveryItem,
            bool autoCloseConnection = true, //not used in this mailer
            CancellationToken token  = default(CancellationToken))
        {
            var sgFrom = new EmailAddress(deliveryItem.FromEmailAddress, deliveryItem.FromDisplayName);

            var sgTo      = new EmailAddress(deliveryItem.ToEmailAddress, deliveryItem.ToDisplayName);
            var sgMessage = new SendGridMessage
            {
                From = sgFrom,

                Personalizations = new List <Personalization>
                {
                    new Personalization
                    {
                        Tos = new List <EmailAddress> {
                            sgTo
                        },
                        Subject       = deliveryItem.ProcessSubstitutions(deliveryItem.Subject),
                        Substitutions = new Dictionary <string, string>(deliveryItem.Substitutions)
                    }
                }
            };

            if (!string.IsNullOrEmpty(deliveryItem.ReplyToEmailAddress))
            {
                sgMessage.ReplyTo = new EmailAddress(deliveryItem.ReplyToEmailAddress, deliveryItem.ReplyToDisplayName);
            }

            if (deliveryItem.Body is ContentBody body)
            {
                sgMessage.HtmlContent      = deliveryItem.ProcessSubstitutions(body.HtmlContent);
                sgMessage.PlainTextContent = deliveryItem.ProcessSubstitutions(body.PlainTextContent);
            }
            else
            {
                sgMessage.SetTemplateId(((TemplateBody)deliveryItem.Body).TemplateName);
            }


            sgMessage.SetSandBoxMode(Settings.IsSandboxMode);


            await AddAttachmentStreamsAsync(sgMessage, deliveryItem.Attachments, token);

            var sgResponse = await SendToApiAsync(sgMessage, token);


            var isSuccess = sgResponse?.StatusCode == HttpStatusCode.Accepted ||
                            Settings.IsSandboxMode && sgResponse?.StatusCode == HttpStatusCode.OK;

            if (isSuccess)
            {
                return(sgResponse.Headers?.GetValues("X-Message-Id").FirstOrDefault());
            }

            throw new Exception(
                      $"Unable to deliver message; SendGrid response HTTP StatusCode is: {sgResponse?.StatusCode}");
        }
        /// <summary>
        ///     Gets the MIME entity the content body.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="message">The message.</param>
        /// <param name="cbody">The cbody.</param>
        /// <returns>BodyBuilder.</returns>
        public static BodyBuilder GetMimeEntityForContentBody(this BodyBuilder builder, DeliveryItem message,
                                                              ContentBody cbody)
        {
            if (cbody != null)
            {
                builder.TextBody = message.ProcessSubstitutions(cbody.PlainTextContent);
                builder.HtmlBody = message.ProcessSubstitutions(cbody.HtmlContent);
            }

            return(builder);
        }
Example #3
0
        /// <summary>
        ///     Deliver message as an asynchronous operation.
        /// </summary>
        /// <param name="deliveryItem">The delivery item containing the message you wish to send.</param>
        /// <param name="autoCloseConnection">
        ///     If set to <c>true</c> will close connection immediately after delivering the message.
        ///     If caller is sending multiple messages, optionally set to false to leave the mail service connection open.
        /// </param>
        /// <param name="token">The cancellation token.</param>
        /// <returns>Task&lt;String&gt; a service provider specific message ID.</returns>
        /// <remarks>The implementor should return a provider specific ID value.</remarks>
        protected override async Task <string> DeliverMessageAsync(
            DeliveryItem deliveryItem,
            bool autoCloseConnection = true,
            CancellationToken token  = default(CancellationToken))
        {
            var mkMessage = new MimeMessage
            {
                Priority = MessagePriority.Normal,
                Subject  = deliveryItem.ProcessSubstitutions(deliveryItem.Subject)
            };

            mkMessage.From.Add(new MailboxAddress(deliveryItem.FromDisplayName, deliveryItem.FromEmailAddress));

            if (!string.IsNullOrEmpty(deliveryItem.ReplyToEmailAddress))
            {
                mkMessage.ReplyTo.Add(
                    new MailboxAddress(deliveryItem.ReplyToDisplayName, deliveryItem.ReplyToEmailAddress));
            }
            try
            {
                var box = string.IsNullOrEmpty(deliveryItem.ToDisplayName)
                    ? new MailboxAddress(deliveryItem.ToEmailAddress)
                    : new MailboxAddress(deliveryItem.ToDisplayName, deliveryItem.ToEmailAddress);
                mkMessage.To.Add(box);
            }
            catch (FormatException)
            {
                Logger.LogError(1,
                                "Invalid email address format: {name} <{address}> Subject: {subject}",
                                deliveryItem.ToDisplayName, deliveryItem.ToEmailAddress, deliveryItem.Subject);
                throw;
            }

            mkMessage.Body = (await new BodyBuilder()
                              .GetMkBody(deliveryItem, Settings, Logger, token))
                             .AddMkAttachmentStreams(deliveryItem.Attachments)
                             .ToMessageBody();

            return(await SendSmtpMessageAsync(mkMessage, autoCloseConnection, token));
        }