コード例 #1
3
        /// <summary>
        ///     Creates a MailMessage for the current MailAttribute instance.
        /// </summary>
        protected SendGridMessage GenerateProspectiveMailMessage(MailAttributes mail)
        {
            // Basic message attributes
            var message = new SendGridMessage
            {
                From = mail.From,
                To = mail.To.ToArray(),
                Cc = mail.Cc.ToArray(),
                Bcc = mail.Bcc.ToArray(),
                ReplyTo = mail.ReplyTo.ToArray(),
                Subject = mail.Subject,
                Headers = (Dictionary<string, string>)mail.Headers
            };

            // Message content
            foreach (var view in mail.AlternateViews)
            {
                var reader = new StreamReader(view.ContentStream);

                var body = reader.ReadToEnd();

                if (view.ContentType.MediaType == MediaTypeNames.Text.Plain)
                {
                    message.Text = body;
                }
                if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
                {
                    message.Html = body;
                }
            }

            // Attachments
            foreach (
                var mailAttachment in
                    mail.Attachments.Select(
                        attachment =>
                        AttachmentCollection.ModifyAttachmentProperties(attachment.Key, attachment.Value, false)))
            {
                using (var stream = new MemoryStream())
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    mailAttachment.ContentStream.CopyTo(stream);
                    message.AddAttachment(stream, mailAttachment.Name);
                }
            }
            return message;
        }
コード例 #2
2
        public MailAttributes Execute(MailAttributes mailAttributes)
        {
            var newMailAttributes = new MailAttributes(mailAttributes);

            foreach (var view in mailAttributes.AlternateViews)
            {
                using (var reader = new StreamReader(view.ContentStream))
                {
                    var body = reader.ReadToEnd();

                    if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
                    {
                        var inlinedCssString = PreMailer.MoveCssInline(body);

                        byte[] byteArray = Encoding.UTF8.GetBytes(inlinedCssString.Html);
                        var stream = new MemoryStream(byteArray);
                        
                        var newAlternateView = new AlternateView(stream, MediaTypeNames.Text.Html);
                        newMailAttributes.AlternateViews.Add(newAlternateView);
                    }
                    else
                    {
                        newMailAttributes.AlternateViews.Add(view);
                    }
                }
            }

            return newMailAttributes;
        }
コード例 #3
1
        /// <summary>
        ///     Creates a MailMessage for the current MailAttribute instance.
        /// </summary>
        protected EmailMessage GenerateProspectiveMailMessage(MailAttributes mail)
        {
            //create base message
            var message = new EmailMessage
            {
                from_name = mail.From.DisplayName,
                from_email = mail.From.Address,
                to = mail.To.Union(mail.Cc).Select(t => new EmailAddress(t.Address, t.DisplayName)),
                bcc_address = mail.Bcc.Any() ? mail.Bcc.First().Address : null,
                subject = mail.Subject,
                important = mail.Priority == MailPriority.High ? true : false
            };

            // We need to set Reply-To as a custom header
            if (mail.ReplyTo.Any())
            {
                message.AddHeader("Reply-To", string.Join(" , ", mail.ReplyTo));
            }

            // Adding content to the message
            foreach (var view in mail.AlternateViews)
            {
                var reader = new StreamReader(view.ContentStream, Encoding.UTF8, true, 1024, true);
                
                    var body = reader.ReadToEnd();

                    if (view.ContentType.MediaType == MediaTypeNames.Text.Plain)
                    {
                        message.text = body;
                    }
                    if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
                    {
                        message.html = body;
                    }      
            }

            // Going through headers and adding them to the message
            mail.Headers.ToList().ForEach(h => message.AddHeader(h.Key, h.Value));

            // Adding the attachments
            var attachments = new List<email_attachment>();
            foreach (var mailAttachment in mail.Attachments.Select(attachment => Utils.AttachmentCollection.ModifyAttachmentProperties(attachment.Key, attachment.Value, false)))
            {
                using (var stream = new MemoryStream())
                {
                    mailAttachment.ContentStream.CopyTo(stream);
                    var base64Data = Convert.ToBase64String(stream.ToArray());
                    attachments.Add(new email_attachment
                    {
                        content = base64Data,
                        name = mailAttachment.Name,
                        type = mailAttachment.ContentType.MediaType,
                    });
                }
            }

            message.attachments = attachments;

            return message;
        }
コード例 #4
0
        public virtual List <IMailResponse> Send(MailAttributes mailAttributes)
        {
            var mail     = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List <IMailResponse>();


            List <EmailResult> resp = null;

            var completeEvent = new ManualResetEvent(false);

            ThreadPool.QueueUserWorkItem((obj) =>
            {
                resp = client.SendMessage(new SendMessageRequest(mail)).Result;
                completeEvent.Set();
            });

            completeEvent.WaitOne();

            response.AddRange(resp.Select(result => new MandrillMailResponse
            {
                Email        = result.Email,
                Status       = MandrillMailResponse.GetProspectiveStatus(result.Status.ToString()),
                RejectReason = result.RejectReason,
                Id           = result.Id
            }));

            return(response);
        }
コード例 #5
0
        /// <summary>
        ///     Creates a new EmailResult.  You must call Compile() before this result
        ///     can be successfully delivered.
        /// </summary>
        /// <param name="interceptor">The IMailInterceptor that we will call when delivering MailAttributes.</param>
        /// <param name="sender">The IMailSender that we will use to send MailAttributes.</param>
        /// <param name="mailAttributes"> message who's body needs populating.</param>
        /// <param name="viewName">The view to use when rendering the message body.</param>
        /// <param name="masterName">the main layout</param>
        /// <param name="viewPath">The path where we should search for the view.</param>
        /// <param name="templateService">The template service defining a ITemplateResolver and a TemplateBase</param>
        /// <param name="viewBag">The viewBag is a dynamic object that can transfer data to the view</param>
        /// <param name="messageEncoding"></param>
        public RazorEmailResult(MailAttributes mailAttributes, string viewName,
                                Encoding messageEncoding, string masterName,
                                string viewPath, ITemplateService templateService, DynamicViewBag viewBag)
        {
            if (mailAttributes == null)
            {
                throw new ArgumentNullException("mailAttributes");
            }

            if (string.IsNullOrWhiteSpace(viewName))
            {
                throw new ArgumentNullException("viewName");
            }


            if (templateService == null)
            {
                throw new ArgumentNullException("templateService");
            }

            _mailAttributes = mailAttributes;
            _viewName       = viewName;
            _masterName     = masterName;
            _viewPath       = viewPath;

            _templateService = templateService;
            _messageEncoding = messageEncoding;

            _viewBag = viewBag;
        }
コード例 #6
0
        /// <summary>
        ///     Creates a new EmailResult.  You must call ExecuteCore() before this result
        ///     can be successfully delivered.
        /// </summary>
        /// <param name="interceptor">The IMailInterceptor that we will call when delivering MailAttributes.</param>
        /// <param name="sender">The IMailSender that we will use to send MailAttributes.</param>
        /// <param name="mailAttributes">The MailAttributes messageBase who's body needs populating.</param>
        /// <param name="viewName">The view to use when rendering the messageBase body (can be null)</param>
        /// <param name="masterName">The maste rpage to use when rendering the messageBase body (can be null)</param>
        /// <param name="messageEncoding">The encoding to use when rendering a messageBase.</param>
        /// <param name="trimBody">Whether or not we should trim whitespace from the beginning and end of the messageBase body.</param>
        public EmailResult(IMailInterceptor interceptor, IMailSender sender, MailAttributes mailAttributes, string viewName,
                           string masterName, Encoding messageEncoding, bool trimBody)
        {
            if (interceptor == null)
            {
                throw new ArgumentNullException("interceptor");
            }

            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }

            if (mailAttributes == null)
            {
                throw new ArgumentNullException("mailAttributes");
            }

            ViewName         = viewName ?? ViewName;
            MasterName       = masterName ?? MasterName;
            _messageEncoding = messageEncoding;
            _mailAttributes  = mailAttributes;
            _sender          = sender;
            _interceptor     = interceptor;
            _trimBody        = trimBody;
        }
コード例 #7
0
        public MailAttributes Execute(MailAttributes mailAttributes)
        {
            var newMailAttributes = new MailAttributes(mailAttributes);

            foreach (var view in mailAttributes.AlternateViews)
            {
                using (var reader = new StreamReader(view.ContentStream))
                {
                    var body = reader.ReadToEnd();

                    if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
                    {
                        var inlinedCssString = PreMailer.Net.PreMailer.MoveCssInline(baseUri, body, ignoreElements: ".non-inline");

                        byte[] byteArray = Encoding.UTF8.GetBytes(inlinedCssString.Html);
                        var    stream    = new MemoryStream(byteArray);

                        var newAlternateView = new AlternateView(stream, MediaTypeNames.Text.Html);
                        newMailAttributes.AlternateViews.Add(newAlternateView);
                    }
                    else
                    {
                        newMailAttributes.AlternateViews.Add(view);
                    }
                }
            }

            return(newMailAttributes);
        }
コード例 #8
0
        /// <summary>
        ///     Initializes MailerBase using the default SmtpMailSender and system Encoding.
        /// </summary>
        /// <param name="mailAttributes"></param>
        /// <param name="mailSender">The underlying mail sender to use for delivering mail.</param>
        protected RazorMailerBase(MailAttributes mailAttributes = null, IMailSender mailSender = null)
        {
            MailAttributes = mailAttributes ?? new MailAttributes();
            MailSender     = mailSender ?? new SmtpMailSender();

            ViewBag = new DynamicViewBag();
        }
コード例 #9
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="message">消息体</param>
        /// <param name="publisher">主题</param>
        private void SendMail(IEventMessage message, Topic publisher)
        {
            try
            {
                var request   = new PublishMessageRequest();
                var mailAttrs = new MailAttributes
                {
                    AccountName    = message.Data["AccountName"], // 接件邮箱
                    Subject        = message.Data["Subject"],     // 邮件主题
                    IsHtml         = false,
                    ReplyToAddress = false,
                    AddressType    = 0
                };
                var messageAttrs = new MessageAttributes();
                messageAttrs.MailAttributes = mailAttrs;
                request.MessageAttributes   = messageAttrs;
                request.MessageTag          = message.Tag;
                request.MessageBody         = message.Body;
                publisher.PublishMessage(request);

                // 检查发送结果
                var queue    = _client.CreateQueue(QueueName);
                var response = queue.ReceiveMessage(30);
                XTrace.WriteLine($"发送邮件:{response.Message.Body} ");
            }
            catch (Exception ex)
            {
                XTrace.WriteLine("发送邮件失败。");
                XTrace.WriteException(ex);
            }
        }
コード例 #10
0
        /// <summary>
        ///     Sends SMTPMailMessage asynchronously using tasks.
        /// </summary>
        /// <param name="mailAttributes">The MailAttributes message you wish to send.</param>
        public virtual async Task <List <IMailResponse> > SendAsync(MailAttributes mailAttributes)
        {
            var response = new List <IMailResponse>();

            var mail = GenerateProspectiveMailMessage(mailAttributes);

            try
            {
                _client.SendMailAsync(mail);
                response.AddRange(mail.To.Select(mailAddr => new SmtpMailResponse()
                {
                    Email        = mailAddr.Address,
                    Status       = SmtpMailResponse.GetProspectiveStatus(SmtpStatusCode.Ok.ToString()),
                    RejectReason = null
                }));
            }
            catch (SmtpFailedRecipientsException ex)
            {
                response.AddRange(ex.InnerExceptions.Select(e => new SmtpMailResponse
                {
                    Email        = e.FailedRecipient,
                    Status       = SmtpMailResponse.GetProspectiveStatus(e.StatusCode.ToString()),
                    RejectReason = e.Message
                }));
            }
            return(response);
        }
コード例 #11
0
        public void EmailWithNoViewNameShouldThrow()
        {
            var mockSender = A.Fake<IMailSender>();
            var attribute = new MailAttributes();
            var mailer = new TestMailerBase(attribute, mockSender);

            Assert.Throws<ArgumentNullException>(() => mailer.Email(null));
        }
コード例 #12
0
        public void EmailWithNoViewNameShouldThrow()
        {
            var mockSender = A.Fake <IMailSender>();
            var attribute  = new MailAttributes();
            var mailer     = new TestMailerBase(attribute, mockSender);

            Assert.Throws <ArgumentNullException>(() => mailer.Email(null));
        }
コード例 #13
0
 public static MailAttributes CreateMailAttributes(MailAttributes mailAttributes)
 {
     if (mailAttributes == null)
     {
         mailAttributes = new MailAttributes();
     }
     return(mailAttributes);
 }
コード例 #14
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="mailAttributes"></param>
 /// <param name="mailSender"></param>
 /// <param name="templateResolver"></param>
 protected HBSMailerBase(MailAttributes mailAttributes = null, IMailSender mailSender = null, ITemplateResolver templateResolver = null, ITemplateService templateService = null)
 {
     MailAttributes    = mailAttributes ?? new MailAttributes();
     MailSender        = mailSender ?? new SmtpMailSender();
     _templateResolver = templateResolver;
     ViewBag           = new ExpandoObject();
     _templateService  = templateService;
 }
コード例 #15
0
        /// <summary>
        ///     Creates a MailMessage for the current SmtpMailAttribute instance.
        /// </summary>
        protected MailMessage GenerateProspectiveMailMessage(MailAttributes mail)
        {
            var message = new MailMessage();

            for (var i = 0; i < mail.To.Count; i++)
            {
                message.To.Add(mail.To[i]);
            }

            for (var i = 0; i < mail.Cc.Count; i++)
            {
                message.CC.Add(mail.Cc[i]);
            }

            for (var i = 0; i < mail.Bcc.Count; i++)
            {
                message.Bcc.Add(mail.Bcc[i]);
            }

            for (var i = 0; i < mail.ReplyTo.Count; i++)
            {
                message.ReplyToList.Add(mail.ReplyTo[i]);
            }

            // From is optional because it could be set in <mailSettings>
            if (!String.IsNullOrWhiteSpace(mail.From.Address))
            {
                message.From = new MailAddress(mail.From.Address, mail.From.DisplayName);
            }


            message.Subject         = mail.Subject;
            message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1"); //https://connect.microsoft.com/VisualStudio/feedback/details/785710/mailmessage-subject-incorrectly-encoded-in-utf-8-base64
            message.BodyEncoding    = Encoding.UTF8;
            message.Priority        = mail.Priority;

            foreach (var kvp in mail.Headers)
            {
                message.Headers[kvp.Key] = kvp.Value;
            }

            foreach (var kvp in mail.Attachments)
            {
                message.Attachments.Add(Utils.AttachmentCollection.ModifyAttachmentProperties(kvp.Key, kvp.Value, false));
            }

            foreach (var kvp in mail.Attachments.Inline)
            {
                message.Attachments.Add(Utils.AttachmentCollection.ModifyAttachmentProperties(kvp.Key, kvp.Value, true));
            }

            foreach (var view in mail.AlternateViews)
            {
                message.AlternateViews.Add(view);
            }

            return(message);
        }
コード例 #16
0
        public void MailContextConstructorSetsUpObjectProperly()
        {
            var mail = new MailAttributes {From = new MailAddress("*****@*****.**")};
            mail.To.Add(new MailAddress("*****@*****.**"));

            var context = new MailSendingContext(mail);

            Assert.AreEqual(mail, context.Mail);
            Assert.False(context.Cancel);
        }
コード例 #17
0
        public void DeliverSynchronouslyNotifiesWhenMailWasSent()
        {
            var sender      = A.Fake <IMailSender>();
            var interceptor = A.Fake <IMailInterceptor>();
            var helper      = new DeliveryHelper(sender, interceptor);
            var mail        = new MailAttributes();

            helper.Deliver(mail);

            A.CallTo(() => interceptor.OnMailSent(mail)).MustHaveHappened();
        }
コード例 #18
0
        public void DeliverNotifiesWhenMailIsBeingSent()
        {
            var sender      = A.Fake <IMailSender>();
            var interceptor = A.Fake <IMailInterceptor>();
            var helper      = new DeliveryHelper(sender, interceptor);
            var mail        = new MailAttributes();

            helper.Deliver(mail);

            A.CallTo(() => interceptor.OnMailSending(A <MailSendingContext> .Ignored)).MustHaveHappened();
        }
コード例 #19
0
        public async void DeliveryAsynchronouslySendsMessage()
        {
            var sender      = A.Fake <IMailSender>();
            var interceptor = A.Fake <IMailInterceptor>();
            var helper      = new DeliveryHelper(sender, interceptor);
            var mail        = new MailAttributes();

            await helper.DeliverAsync(mail);

            A.CallTo(() => sender.SendAsync(mail)).MustHaveHappened();
        }
コード例 #20
0
        public void MultipartMessagesShouldRenderBothViews()
        {
            var mockSender = A.Fake <IMailSender>();
            var attribute  = new MailAttributes();
            var mailer     = new TestMailerBase(attribute, mockSender);

            var email    = mailer.Email("MultipartNoModel");
            var htmlBody = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd().Trim();

            Assert.AreEqual("<p>Testing multipart.</p>", htmlBody);
        }
コード例 #21
0
        public async void DeliverAsynchronouslyNotifiesWhenMailWasSent()
        {
            var sender = A.Fake<IMailSender>();
            var interceptor = A.Fake<IMailInterceptor>();
            var helper = new DeliveryHelper(sender, interceptor);
            var mail = new MailAttributes();

            await helper.DeliverAsync(mail);

            A.CallTo(() => interceptor.OnMailSent(A<MailAttributes>.Ignored)).MustHaveHappened();
        }
コード例 #22
0
        public void WhiteSpaceShouldBeTrimmedWhenRequired()
        {
            var mockSender = A.Fake <IMailSender>();
            var attribute  = new MailAttributes();
            var mailer     = new TestMailerBase(attribute, mockSender);

            var email = mailer.Email("WhitespaceTrimTest", trimBody: true);
            var body  = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd();

            Assert.AreEqual("This thing has leading and trailing whitespace.", body);
        }
コード例 #23
0
        public void RazorViewWithNoModelShouldRenderProperly()
        {
            var mockSender = A.Fake <IMailSender>();
            var attribute  = new MailAttributes();
            var mailer     = new TestMailerBase(attribute, mockSender);

            var email = mailer.Email("TextViewNoModel");
            var body  = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd().Trim();

            Assert.AreEqual("This is a test", body);
        }
コード例 #24
0
        public void DeliverNotifiesWhenMailIsBeingSent()
        {
            var sender = A.Fake<IMailSender>();
            var interceptor = A.Fake<IMailInterceptor>();
            var helper = new DeliveryHelper(sender, interceptor);
            var mail = new MailAttributes();

            helper.Deliver(mail);

            A.CallTo(() => interceptor.OnMailSending(A<MailSendingContext>.Ignored)).MustHaveHappened();
        }
コード例 #25
0
        /// <summary>
        ///     Initializes MailerBase using the defaultMailSender and system Encoding.
        /// </summary>
        /// <param name="mailAttributes"> the mail attributes</param>
        /// <param name="mailSender">The underlying mail sender to use for delivering mail.</param>
        protected MailerBase(MailAttributes mailAttributes = null, IMailSender mailSender = null)
        {
            MailAttributes = mailAttributes ?? new MailAttributes();
            MailSender = mailSender ?? new SmtpMailSender();

            if (System.Web.HttpContext.Current == null) return;
            HttpContextBase = new HttpContextWrapper(System.Web.HttpContext.Current);
            RouteData routeData = RouteTable.Routes.GetRouteData(HttpContextBase) ?? new RouteData();
            var requestContext = new RequestContext(HttpContextBase, routeData);
            base.Initialize(requestContext);
        }
コード例 #26
0
        public void WhiteSpaceShouldBeIncludedWhenRequired()
        {
            var mockSender = A.Fake <IMailSender>();
            var attribute  = new MailAttributes();
            var mailer     = new TestMailerBase(attribute, mockSender);

            var email = mailer.Email("WhitespaceTrimTest", null, false);
            var body  = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd();

            Assert.True(char.IsWhiteSpace(body, 0));
            Assert.True(char.IsWhiteSpace(body, body.Length - 1));
        }
コード例 #27
0
        public void MultipartMessagesShouldRenderBothViews()
        {
            var mockSender = A.Fake<IMailSender>();
            var attribute = new MailAttributes();
            var mailer = new TestMailerBase(attribute, mockSender);

            var email = mailer.Email("MultipartNoModel");
            var textBody = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd().Trim();
            var htmlBody = new StreamReader(email.MailAttributes.AlternateViews[1].ContentStream).ReadToEnd().Trim();

            Assert.AreEqual("Testing multipart.", textBody);
            Assert.AreEqual("<p>Testing multipart.</p>", htmlBody);
        }
コード例 #28
0
        public void MailContextConstructorSetsUpObjectProperly()
        {
            var mail = new MailAttributes {
                From = new MailAddress("*****@*****.**")
            };

            mail.To.Add(new MailAddress("*****@*****.**"));

            var context = new MailSendingContext(mail);

            Assert.AreEqual(mail, context.Mail);
            Assert.False(context.Cancel);
        }
コード例 #29
0
        public IRequest Marshall(PublishMessageRequest publicRequest)
        {
            MemoryStream  stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            writer.WriteStartDocument();
            writer.WriteStartElement(MNSConstants.XML_ROOT_MESSAGE, MNSConstants.MNS_XML_NAMESPACE);
            if (publicRequest.IsSetMessageBody())
            {
                writer.WriteElementString(MNSConstants.XML_ELEMENT_MESSAGE_BODY, publicRequest.MessageBody);
            }
            if (publicRequest.IsSetMessageTag())
            {
                writer.WriteElementString(MNSConstants.XML_ELEMENT_MESSAGE_TAG, publicRequest.MessageTag);
            }
            if (publicRequest.IsSetMessageAttributes())
            {
                MessageAttributes messageAttributes = publicRequest.MessageAttributes;
                writer.WriteStartElement(MNSConstants.XML_ELEMENT_MESSAGE_ATTRIBUTES);
                if (messageAttributes.IsSetMailAttributes())
                {
                    MailAttributes mailAttributes = messageAttributes.MailAttributes;
                    writer.WriteElementString(MNSConstants.XML_ELEMENT_DIRECT_MAIL, mailAttributes.ToJson());
                }
                if (messageAttributes.IsSetSmsAttributes())
                {
                    SmsAttributes smsAttributes = messageAttributes.SmsAttributes;
                    writer.WriteElementString(MNSConstants.XML_ELEMENT_DIRECT_SMS, smsAttributes.ToJson());
                }
                if (messageAttributes.IsSetBatchSmsAttributes())
                {
                    BatchSmsAttributes batchSmsAttributes = messageAttributes.BatchSmsAttributes;
                    writer.WriteElementString(MNSConstants.XML_ELEMENT_DIRECT_SMS, batchSmsAttributes.ToJson());
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();

            stream.Seek(0, SeekOrigin.Begin);

            IRequest request = new DefaultRequest(publicRequest, MNSConstants.MNS_SERVICE_NAME);

            request.HttpMethod    = HttpMethod.POST.ToString();
            request.ContentStream = stream;
            request.ResourcePath  = MNSConstants.MNS_TOPIC_PRE_RESOURCE + publicRequest.TopicName
                                    + MNSConstants.MNS_MESSAGE_SUB_RESOURCE;
            return(request);
        }
コード例 #30
0
        public void PassingAModelShouldWork()
        {
            var mockSender = A.Fake<IMailSender>();
            var attribute = new MailAttributes();
            var mailer = new TestMailerBase(attribute, mockSender);
            var model = new TestModel
            {
                Name = "Foo"
            };

            var email = mailer.Email("TextViewWithModel", model);
            var body = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd().Trim();

            Assert.AreEqual("Your name is:  Foo", body);
        }
コード例 #31
0
        public void PassingAModelShouldWork()
        {
            var mockSender = A.Fake <IMailSender>();
            var attribute  = new MailAttributes();
            var mailer     = new TestMailerBase(attribute, mockSender);
            var model      = new TestModel
            {
                Name = "Foo"
            };

            var email = mailer.Email("TextViewWithModel", model);
            var body  = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd().Trim();

            Assert.AreEqual("Your name is:  Foo", body);
        }
コード例 #32
0
        public virtual async Task <List <IMailResponse> > SendAsync(MailAttributes mailAttributes)
        {
            var mail     = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List <IMailResponse>();

            await _client.SendMessageAsync(mail).ContinueWith(x => response.AddRange(x.Result.Select(result => new MandrillMailResponse
            {
                Email        = result.Email,
                Status       = MandrillMailResponse.GetProspectiveStatus(result.Status.ToString()),
                RejectReason = result.RejectReason,
                Id           = result.Id
            })));

            return(response);
        }
コード例 #33
0
        /// <summary>
        ///     Creates a MailMessage for the current MailAttribute instance.
        /// </summary>
        protected SendGridMessage GenerateProspectiveMailMessage(MailAttributes mail)
        {
            // Basic message attributes
            var message = new SendGridMessage
            {
                From    = mail.From,
                To      = mail.To.ToArray(),
                Cc      = mail.Cc.ToArray(),
                Bcc     = mail.Bcc.ToArray(),
                ReplyTo = mail.ReplyTo.ToArray(),
                Subject = mail.Subject,
                Headers = (Dictionary <string, string>)mail.Headers
            };

            // Message content
            foreach (var view in mail.AlternateViews)
            {
                var reader = new StreamReader(view.ContentStream);

                var body = reader.ReadToEnd();

                if (view.ContentType.MediaType == MediaTypeNames.Text.Plain)
                {
                    message.Text = body;
                }
                if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
                {
                    message.Html = body;
                }
            }

            // Attachments
            foreach (
                var mailAttachment in
                mail.Attachments.Select(
                    attachment =>
                    AttachmentCollection.ModifyAttachmentProperties(attachment.Key, attachment.Value, false)))
            {
                using (var stream = new MemoryStream())
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    mailAttachment.ContentStream.CopyTo(stream);
                    message.AddAttachment(stream, mailAttachment.Name);
                }
            }
            return(message);
        }
コード例 #34
0
        public virtual List <IMailResponse> Send(MailAttributes mailAttributes)
        {
            var mail     = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List <IMailResponse>();

            var resp = _client.SendMessage(mail);

            response.AddRange(resp.Select(result => new MandrillMailResponse
            {
                Email        = result.Email,
                Status       = MandrillMailResponse.GetProspectiveStatus(result.Status.ToString()),
                RejectReason = result.RejectReason,
                Id           = result.Id
            }));

            return(response);
        }
コード例 #35
0
        public virtual async Task <List <IMailResponse> > SendAsync(MailAttributes mailAttributes)
        {
            var mail     = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List <IMailResponse>();

            await _client.DeliverAsync(mail);

            for (int i = 0; i <= mailAttributes.To.Count; i++)
            {
                response.Add(new SendGridMailResponse
                {
                    Email  = mailAttributes.To[i].Address,
                    Status = "E-mail delivered successfully."
                });
            }
            return(response);
        }
コード例 #36
0
        public void PassingAMailSenderShouldWork()
        {
            var mockSender = A.Fake <IMailSender>();
            var attributes = new MailAttributes();

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new TextViewEngine());

            var mailer = new TestMailerBase(attributes, mockSender);

            mailer.HttpContextBase     = MvcHelper.GetHttpContext("/app/", null, null);
            mailer.MailAttributes.From = new MailAddress("*****@*****.**");
            EmailResult result = mailer.Email("TestView");

            Assert.AreSame(mockSender, mailer.MailSender);
            Assert.AreSame(mockSender, result.MailSender);
        }
コード例 #37
0
        /// <summary>
        ///     Creates a new EmailResult.  You must call ExecuteCore() before this result
        ///     can be successfully delivered.
        /// </summary>
        /// <param name="interceptor">The IMailInterceptor that we will call when delivering MailAttributes.</param>
        /// <param name="sender">The IMailSender that we will use to send MailAttributes.</param>
        /// <param name="mailAttributes">The MailAttributes messageBase who's body needs populating.</param>
        /// <param name="viewName">The view to use when rendering the messageBase body (can be null)</param>
        /// <param name="masterName">The maste rpage to use when rendering the messageBase body (can be null)</param>
        /// <param name="messageEncoding">The encoding to use when rendering a messageBase.</param>
        /// <param name="trimBody">Whether or not we should trim whitespace from the beginning and end of the messageBase body.</param>
        public EmailResult(IMailInterceptor interceptor, IMailSender sender, MailAttributes mailAttributes, string viewName,
            string masterName, Encoding messageEncoding, bool trimBody)
        {
            if (interceptor == null)
                throw new ArgumentNullException("interceptor");

            if (sender == null)
                throw new ArgumentNullException("sender");

            if (mailAttributes == null)
                throw new ArgumentNullException("mailAttributes");

            ViewName = viewName ?? ViewName;
            MasterName = masterName ?? MasterName;
            _messageEncoding = messageEncoding;
            _mailAttributes = mailAttributes;
            _sender = sender;
            _interceptor = interceptor;
            _trimBody = trimBody;
        }
コード例 #38
0
        /// <summary>
        ///     Creates a MailMessage for the current SmtpMailAttribute instance.
        /// </summary>
        protected MailMessage GenerateProspectiveMailMessage(MailAttributes mail)
        {
            var message = new MailMessage();

            for (var i = 0; i < mail.To.Count; i++)
                message.To.Add(mail.To[i]);

            for (var i = 0; i < mail.Cc.Count; i++)
                message.CC.Add(mail.Cc[i]);

            for (var i = 0; i < mail.Bcc.Count; i++)
                message.Bcc.Add(mail.Bcc[i]);

            for (var i = 0; i < mail.ReplyTo.Count; i++)
                message.ReplyToList.Add(mail.ReplyTo[i]);

            // From is optional because it could be set in <mailSettings>
            if (mail.From != null && !String.IsNullOrWhiteSpace(mail.From.Address))
                message.From = new MailAddress(mail.From.Address, mail.From.DisplayName);


            message.Subject = mail.Subject;
            message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1"); //https://connect.microsoft.com/VisualStudio/feedback/details/785710/mailmessage-subject-incorrectly-encoded-in-utf-8-base64
            message.BodyEncoding = Encoding.UTF8;
            message.Priority = mail.Priority;

            foreach (var kvp in mail.Headers)
                message.Headers[kvp.Key] = kvp.Value;

            foreach (var kvp in mail.Attachments)
                message.Attachments.Add(Utils.AttachmentCollection.ModifyAttachmentProperties(kvp.Key, kvp.Value, false));

            foreach (var kvp in mail.Attachments.Inline)
                message.Attachments.Add(Utils.AttachmentCollection.ModifyAttachmentProperties(kvp.Key, kvp.Value, true));

            foreach (var view in mail.AlternateViews)
                message.AlternateViews.Add(view);

            return message;
        }
コード例 #39
0
        /// <summary>
        ///     Creates a MailMessage for the current MailAttribute instance.
        /// </summary>
        protected EmailMessage GenerateProspectiveMailMessage(MailAttributes mail)
        {
            var idnmapping = new IdnMapping();

            var emailAddresses = mail.To
                .Select(
                    t =>
                    {
                        var domainSplit = t.Address.Split('@');
                        return new EmailAddress(domainSplit[0] + "@" + idnmapping.GetAscii(domainSplit[1])) { type = "to" };
                    })
                .Union(
                    mail.Cc.Select(
                        t =>
                        {
                            var domainSplit = t.Address.Split('@');
                            return new EmailAddress(domainSplit[0] + "@" + idnmapping.GetAscii(domainSplit[1])) { type = "cc" };
                        }))
                .Union(
                    mail.Bcc.Select(
                        t =>
                        {
                            var domainSplit = t.Address.Split('@');
                            return new EmailAddress(domainSplit[0] + "@" + idnmapping.GetAscii(domainSplit[1])) { type = "bcc" };
                        }));       

            //create base message
            var message = new EmailMessage
            {
                from_name = mail.From.DisplayName,
                from_email = mail.From.Address,
                to = emailAddresses,
                subject = mail.Subject,
                important = mail.Priority == MailPriority.High,
                preserve_recipients = true
            };

            // We need to set Reply-To as a custom header
            if (mail.ReplyTo.Any())
            {
                message.AddHeader("Reply-To", string.Join(" , ", mail.ReplyTo));
            }

            // Adding content to the message
            foreach (var view in mail.AlternateViews)
            {
                var reader = new StreamReader(view.ContentStream, Encoding.UTF8, true, 1024, true);
                
                    var body = reader.ReadToEnd();

                    if (view.ContentType.MediaType == MediaTypeNames.Text.Plain)
                    {
                        message.text = body;
                    }
                    if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
                    {
                        message.html = body;
                    }      
            }

            // Going through headers and adding them to the message
            mail.Headers.ToList().ForEach(h => message.AddHeader(h.Key, h.Value));

            // Adding the attachments
            var attachments = new List<email_attachment>();
            foreach (var mailAttachment in mail.Attachments.Select(attachment => Utils.AttachmentCollection.ModifyAttachmentProperties(attachment.Key, attachment.Value, false)))
            {
                using (var stream = new MemoryStream())
                {
                    mailAttachment.ContentStream.CopyTo(stream);
                    var base64Data = Convert.ToBase64String(stream.ToArray());
                    attachments.Add(new email_attachment
                    {
                        content = base64Data,
                        name = ReplaceGermanCharacters(mailAttachment.Name),
                        type = mailAttachment.ContentType.MediaType,
                    });
                }
            }

            message.attachments = attachments;

            return message;
        }
コード例 #40
0
        public async void DeliveryAsynchronouslySendsMessage()
        {
            var sender = A.Fake<IMailSender>();
            var interceptor = A.Fake<IMailInterceptor>();
            var helper = new DeliveryHelper(sender, interceptor);
            var mail = new MailAttributes();

            await helper.DeliverAsync(mail);

            A.CallTo(() => sender.SendAsync(mail)).MustHaveHappened();
        }
コード例 #41
0
        public virtual async Task<List<IMailResponse>> SendAsync(MailAttributes mailAttributes)
        {
            if (_interceptor != null)
                _interceptor.OnMailSending(new MailSendingContext(mailAttributes));

            var mail = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List<IMailResponse>();

            await _client.DeliverAsync(mail);

            for (int i = 0; i <= mailAttributes.To.Count; i++)
            {
                response.Add(new SendGridMailResponse
                {
                    Email = mailAttributes.To[i].Address,
                    Status = "E-mail delivered successfully."
                });
            }
            return response;
        }
コード例 #42
0
        public void WhiteSpaceShouldBeIncludedWhenRequired()
        {
            var mockSender = A.Fake<IMailSender>();
            var attribute = new MailAttributes();
            var mailer = new TestMailerBase(attribute, mockSender);

            var email = mailer.Email("WhitespaceTrimTest", null, false);
            var body = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd();

            Assert.True(char.IsWhiteSpace(body,0));
            Assert.True(char.IsWhiteSpace(body, body.Length-1));
        }
コード例 #43
0
        public void WhiteSpaceShouldBeTrimmedWhenRequired()
        {
            var mockSender = A.Fake<IMailSender>();
            var attribute = new MailAttributes();
            var mailer = new TestMailerBase(attribute, mockSender);

            var email = mailer.Email("WhitespaceTrimTest", trimBody: true);
            var body = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd();

            Assert.AreEqual("This thing has leading and trailing whitespace.", body);
        }
コード例 #44
0
        public virtual List<IMailResponse> Send(MailAttributes mailAttributes)
        {
            var mail = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List<IMailResponse>();

            var resp = _client.SendMessage(mail);
            response.AddRange(resp.Select(result => new MandrillMailResponse
            {
                Email = result.Email,
                Status = MandrillMailResponse.GetProspectiveStatus(result.Status.ToString()),
                RejectReason = result.RejectReason,
                Id = result.Id
            }));

            return response;
        }
コード例 #45
0
        public void PassingAMailSenderShouldWork()
        {
            var mockSender = A.Fake<IMailSender>();
            var attributes = new MailAttributes();
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new TextViewEngine());

            var mailer = new TestMailerBase(attributes, mockSender);
            mailer.HttpContextBase = MvcHelper.GetHttpContext("/app/", null, null);
            mailer.MailAttributes.From = new MailAddress("*****@*****.**");
            EmailResult result = mailer.Email("TestView");

            Assert.AreSame(mockSender, mailer.MailSender);
            Assert.AreSame(mockSender, result.MailSender);
        }
コード例 #46
0
 /// <summary>
 ///     This method is called after each mail is sent.
 /// </summary>
 /// <param name="mail">The mail that was sent.</param>
 protected virtual void OnMailSent(MailAttributes mail)
 {
 }
コード例 #47
0
        public void RazorViewWithNoModelShouldRenderProperly()
        {
            var mockSender = A.Fake<IMailSender>();
            var attribute = new MailAttributes();
            var mailer = new TestMailerBase(attribute, mockSender);

            var email = mailer.Email("TextViewNoModel");
            var body = new StreamReader(email.MailAttributes.AlternateViews[0].ContentStream).ReadToEnd().Trim();

            Assert.AreEqual("This is a test", body);
        }
コード例 #48
0
 void IMailInterceptor.OnMailSent(MailAttributes mail)
 {
     OnMailSent(mail);
 }
コード例 #49
0
 public TestMailerBase(MailAttributes attributes = null, IMailSender sender = null)
     : base(attributes, sender)
 {
 }
コード例 #50
0
 private void AsyncSendCompleted(MailAttributes mail)
 {
     _interceptor.OnMailSent(mail);
 }
コード例 #51
0
        /// <summary>
        ///     Sends SMTPMailMessage synchronously.
        /// </summary>
        /// <param name="mailAttributes">The MailAttributes you wish to send.</param>
        public virtual List<IMailResponse> Send(MailAttributes mailAttributes)
        {
            var response = new List<IMailResponse>();

            var mail = GenerateProspectiveMailMessage(mailAttributes);
            try
            {
                _client.Send(mail);
                response.AddRange(mail.To.Select(mailAddr => new SmtpMailResponse()
                {
                    Email = mailAddr.Address,
                    Status = SmtpMailResponse.GetProspectiveStatus(SmtpStatusCode.Ok.ToString()),
                    RejectReason = null
                }));
            }
            catch (SmtpFailedRecipientsException ex)
            {
                response.AddRange(ex.InnerExceptions.Select(e => new SmtpMailResponse
                {
                    Email = e.FailedRecipient,
                    Status = SmtpMailResponse.GetProspectiveStatus(e.StatusCode.ToString()),
                    RejectReason = e.Message
                }));
            }
            return response;
        }
コード例 #52
0
        public virtual List<IMailResponse> Send(MailAttributes mailAttributes)
        {
            var mail = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List<IMailResponse>();

            _client.Deliver(mail);

            for (int i = 0; i < mailAttributes.To.Count; i++)
            {
                response.Add(new SendGridMailResponse
                {
                    Email = mailAttributes.To[i].Address,
                    Status = "E-mail delivered successfully."
                });
            }
            return response;
        }
コード例 #53
0
        public virtual async Task<List<IMailResponse>> SendAsync(MailAttributes mailAttributes)
        {
            var mail = GenerateProspectiveMailMessage(mailAttributes);
            var response = new List<IMailResponse>();

            await _client.SendMessageAsync(mail).ContinueWith(x => response.AddRange(x.Result.Select(result => new MandrillMailResponse
            {
                Email = result.Email,
                Status = MandrillMailResponse.GetProspectiveStatus(result.Status.ToString()),
                RejectReason = result.RejectReason,
                Id = result.Id
            })));

            return response;
        }