Example #1
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);
        }