Пример #1
0
        public void BuildEmailContent_ShouldThrowArgumentNullException_WhenSubjectMissing()
        {
            //Arrange

            //Act
            Assert.Throws <ArgumentNullException>("subject", () => _factory.BuildEmailContent("", "Testing"));
        }
        /// <inheritdoc />
        public MimeMessage CreateFromMessage(string from, string to, IEnumerable <string> cc, string subject, string bodyHtml, string templateName = "")
        {
            //Validate inputs
            if (string.IsNullOrEmpty(from))
            {
                throw new ArgumentNullException(nameof(from));
            }
            if (string.IsNullOrEmpty(to))
            {
                throw new ArgumentNullException(nameof(to));
            }
            if (string.IsNullOrEmpty(subject))
            {
                throw new ArgumentNullException(nameof(subject));
            }
            if (string.IsNullOrEmpty(bodyHtml))
            {
                throw new ArgumentNullException(nameof(bodyHtml));
            }

            //Convert
            var toSend = new MimeMessage();

            toSend.From.Add(MailboxAddress.Parse(from));
            toSend.To.Add(MailboxAddress.Parse(to));

            //Add CC's if needed
            if (cc != null)
            {
                foreach (var item in cc)
                {
                    try
                    {
                        toSend.Cc.Add(MailboxAddress.Parse(item));
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, $"Unable to add {item} to email copy list");
                    }
                }
            }

            if (_serviceOptions.AddEnvironmentSuffix && !_hostingEnvironment.IsProduction())
            {
                toSend.Subject = $"{subject} ({_hostingEnvironment.EnvironmentName})";
            }
            else
            {
                toSend.Subject = subject;
            }

            //Perform templating
            if (_serviceOptions.AlwaysTemplateEmails && string.IsNullOrEmpty(templateName))
            {
                bodyHtml = _emailTemplateFactory.BuildEmailContent(toSend.Subject, bodyHtml);
            }
            else if (!string.IsNullOrEmpty(templateName))
            {
                bodyHtml = _emailTemplateFactory.BuildEmailContent(toSend.Subject, bodyHtml,
                                                                   templateName: templateName);
            }

            var bodyBuilder = new BodyBuilder {
                HtmlBody = bodyHtml
            };

            toSend.Body = bodyBuilder.ToMessageBody();
            return(toSend);
        }