A message destined for the Postmark service.
        public void Can_send_batched_messages()
        {
            var postmark = new PostmarkClient(_serverToken);

            var first = new PostmarkMessage
            {
                To = _to,
                From = _from, // This must be a verified sender signature
                Subject = Subject,
                TextBody = TextBody,
                HtmlBody = HtmlBody
            };
            var second = new PostmarkMessage
            {
                To = _to,
                From = _from, // This must be a verified sender signature
                Subject = Subject,
                TextBody = TextBody,
                HtmlBody = HtmlBody
            };

            var responses = postmark.SendMessages(first, second);
            Assert.AreEqual(2, responses.Count());

            foreach (var response in responses)
            {
                Assert.IsNotNull(response);
                Assert.IsNotNullOrEmpty(response.Message);
                Assert.IsTrue(response.Status == PostmarkStatus.Success);
                Console.WriteLine("Postmark -> {0}", response.Message);
            }
        }
Esempio n. 2
0
        public bool SendEmail(string from, string replyTo, string subject, string body, string to)
        {
            try
            {
                const string postmarkApiKey = "30ddd0b0-0b9a-432e-a892-3c8739aabf0c";

                var message = new PostmarkMessage
                {
                    From = from.Trim(),
                    To = to.Trim(),
                    Subject = subject,
                    HtmlBody = body,
                    TextBody = body,
                    ReplyTo = replyTo ?? from
                };

                var client = new PostmarkClient(postmarkApiKey.Trim());

                var response = client.SendMessage(message);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
        public void Can_detect_html_in_message()
        {
            var message = new PostmarkMessage(_from, _to, _subject, "Have a <b>great</b> day!");

            Assert.IsNotNull(message);
            Assert.IsTrue(IsBodyHtml(message));
        }
        public void Can_detect_plain_text_message()
        {
            var message = new PostmarkMessage(_from, _to, Subject, "Have a great day!");

            Assert.IsNotNull(message);
            Assert.IsFalse(IsBodyHtml(message));
        }
        /// <summary>
        /// Sends a message through the Postmark API.
        /// All email addresses must be valid, and the sender must be
        /// a valid sender signature according to Postmark. To obtain a valid
        /// sender signature, log in to Postmark and navigate to:
        /// http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name="from">An email address for a sender.</param>
        /// <param name="to">An email address for a recipient.</param>
        /// <param name="subject">The message subject line.</param>
        /// <param name="body">The message body.</param>
        /// <param name="headers">A collection of additional mail headers to send with the message.</param>
        /// <returns>A <see cref = "PostmarkResponse" /> with details about the transaction.</returns>
        public static async Task <PostmarkResponse> SendMessageAsync(this PostmarkClient client,
                                                                     string from, string to, string subject, string body, IDictionary <string, string> headers = null)
        {
            var message = new PostmarkMessage(from, to, subject, body, headers);

            return(await client.SendMessageAsync(message));
        }
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "from">An email address for a sender.</param>
        /// <param name = "to">An email address for a recipient.</param>
        /// <param name = "subject">The message subject line.</param>
        /// <param name = "body">The message body.</param>
        /// <param name = "headers">A collection of additional mail headers to send with the message.</param>
        /// <returns>A <see cref = "PostmarkResponse" /> with details about the transaction.</returns>
        public PostmarkResponse SendMessage(string from, string to, string subject, string body,
                                            NameValueCollection headers)
        {
            var message = new PostmarkMessage(from, to, subject, body, headers);

            return(SendMessage(message));
        }
        private PostmarkMessage ConstructMessage(string inboundAddress, int number = 0)
        {
            var message = new PostmarkMessage()
            {
                From = WRITE_TEST_SENDER_EMAIL_ADDRESS,
                To = WRITE_TEST_SENDER_EMAIL_ADDRESS,
                Cc = WRITE_TEST_EMAIL_RECIPIENT_ADDRESS,
                Bcc = "*****@*****.**",
                Subject = String.Format("Integration Test - {0} - Message #{1}", TESTING_DATE, number),
                HtmlBody = String.Format("Testing the Postmark .net client, <b>{0}</b>", TESTING_DATE),
                TextBody = "This is plain text.",
                TrackOpens = true,
                Headers = new HeaderCollection(){
                  {  "X-Integration-Testing-Postmark-Type-Message" , TESTING_DATE.ToString("o")}
                },
                ReplyTo = inboundAddress,
                Tag = "integration-testing"
            };

            var content = "{ \"name\" : \"data\", \"age\" : null }";

            message.Attachments.Add(new PostmarkMessageAttachment()
            {
                ContentType = "application/json",
                Name = "test.json",
                Content = Convert.ToBase64String(Encoding.UTF8.GetBytes(content))
            });
            return message;
        }
Esempio n. 8
0
        /// <summary>
        /// Add a file from the specified path to this message.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="path"></param>
        /// <param name="contentType"></param>
        /// <param name="contentId"></param>
        public static void AddAttachment(this PostmarkMessage message,
                                         string path, string contentType = null, string contentId = null)
        {
            var fi      = new FileInfo(path);
            var content = File.ReadAllBytes(path);

            message.AddAttachment(content, fi.Name, contentType, contentId);
        }
Esempio n. 9
0
        public string SendCriticalErrorEmail(string sendTo, string sendFrom, string dateTimeStamp, string errorInformation, string postMarkAPIKey)
        {
            _logger.DebugFormat("Sending critical error to: {0}", sendTo);

             // Send a critical error email
             string returnMessage = string.Empty;

             // Build the message
             StringBuilder oSB = new StringBuilder();
             oSB.AppendLine("As of " + dateTimeStamp + " there was a critical error in the Invoice Processing Service.");
             oSB.AppendLine("<br/>");
             oSB.AppendLine("<br/>");
             oSB.AppendLine("Error Information:");
             oSB.AppendLine("<br/>");
             oSB.AppendLine("<br/>");
             oSB.AppendLine(errorInformation);

             string finalBody = oSB.ToString();

             string emailSubject = "Invoice Processing Critical Service Error - " + dateTimeStamp;
             string postMarkServerTokenDesc = "X-Postmark-Server-Token";

             // Build the email
             PostmarkMessage message = new PostmarkMessage(sendFrom, sendTo, emailSubject, finalBody);
             try
             {

            PostmarkMessage newMessage = new PostmarkMessage
            {
               From = sendFrom,
               To = sendTo,
               Subject = emailSubject,
               HtmlBody = finalBody,
               TextBody = string.Empty,
               ReplyTo = sendFrom,
               Headers = new NameValueCollection { { postMarkServerTokenDesc, postMarkAPIKey } }
            };

            PostmarkClient client = new PostmarkClient(postMarkAPIKey);
            PostmarkResponse response = client.SendMessage(newMessage);

            // Set the response information
            string responseMessage = response.Status.ToString();

             }//
             catch (PostmarkDotNet.Validation.ValidationException exPM)
             {
            returnMessage = exPM.ToString();
            _logger.ErrorFormat("Postmark validation error sending critical error email: {0}", returnMessage);
             }
             catch (Exception ex)
             {
            returnMessage = ex.ToString();
            _logger.ErrorFormat("Exception sending critical error email: {0}", returnMessage);
             }

             return returnMessage;
        }
Esempio n. 10
0
 private static void CleanPostmarkMessage(PostmarkMessage message)
 {
     message.From = message.From.Trim();
     if (!string.IsNullOrEmpty(message.To))
     {
         message.To = message.To.Trim();
     }
     message.Subject = message.Subject != null?message.Subject.Trim() : "";
 }
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "message">A prepared message instance</param>
        /// <param name="callback">The callback invoked when a response is received from the API</param>
        public void SendMessage(PostmarkMessage message, Action <PostmarkResponse> callback)
        {
            var request = NewEmailRequest();

            CleanPostmarkMessage(message);

            request.Entity = message;

            BeginGetPostmarkResponse(request, callback);
        }
Esempio n. 12
0
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "message">A prepared message instance.</param>
        /// <returns></returns>
        public PostmarkResponse SendMessage(PostmarkMessage message)
        {
            var request = NewEmailRequest();

            CleanPostmarkMessage(message);

            request.Entity = message;

            return(GetPostmarkResponse(request));
        }
        /// <summary>
        /// Sends a message through the Postmark API.
        /// All email addresses must be valid, and the sender must be
        /// a valid sender signature according to Postmark. To obtain a valid
        /// sender signature, log in to Postmark and navigate to:
        /// http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name="client">The postmark client instance on which to do the send.</param>
        /// <param name="from">An email address for a sender.</param>
        /// <param name="to">An email address for a recipient.</param>
        /// <param name="subject">The message subject line.</param>
        /// <param name="textBody">The Plain Text Body to be used for the message, this may be null if HtmlBody is set.</param>
        /// <param name="htmlBody">The HTML Body to be used for the message, this may be null if TextBody is set.</param>
        /// <param name="headers">A collection of additional mail headers to send with the message.</param>
        /// <returns>A <see cref = "PostmarkResponse" /> with details about the transaction.</returns>
        public static async Task <PostmarkResponse> SendMessageAsync(this PostmarkClient client,
                                                                     string from, string to, string subject, string textBody, string htmlBody,
                                                                     IDictionary <string, string> headers  = null,
                                                                     IDictionary <string, string> metadata = null)
        {
            var message = new PostmarkMessage(from, to, subject, textBody, htmlBody,
                                              new HeaderCollection(headers), metadata);

            return(await client.SendMessageAsync(message));
        }
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "message">A prepared message instance</param>
        /// <param name="callback">The callback invoked when a response is received from the API</param>
        public void SendMessage(PostmarkMessage message, Action<PostmarkResponse> callback)
        {
            var request = NewEmailRequest();

            CleanPostmarkMessage(message);

            request.Entity = message;

            BeginGetPostmarkResponse(request, callback);
        }
Esempio n. 15
0
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "message">A prepared message instance</param>
        /// <returns></returns>
        public IAsyncResult BeginSendMessage(PostmarkMessage message)
        {
            var request = NewEmailRequest();

            CleanPostmarkMessage(message);

            request.Entity = message;

            return(BeginGetPostmarkResponse(request));
        }
        public void Can_generate_postmarkmessage_from_mailmessage()
        {
            var mm = new MailMessage
                         {
                             Subject = "test",
                             Body = "test"
                         };
            mm.Headers.Add ("X-PostmarkTag", "mytag");

            var pm = new PostmarkMessage (mm);
            Assert.AreEqual (mm.Subject, pm.Subject);
            Assert.AreEqual (mm.Body, pm.TextBody);
            Assert.AreEqual ("mytag", pm.Tag);
        }
Esempio n. 17
0
        private static void GetMailMessageBcc(PostmarkMessage m, MailMessage message)
        {
            var sb = new StringBuilder(0);

            if (message.Bcc.Count > 0)
            {
                foreach (var bcc in message.Bcc)
                {
                    sb.AppendFormat("{0},", bcc.Address);
                }
            }

            m.Bcc = sb.ToString();
        }
Esempio n. 18
0
        public void SendEmail(string from, string to, string subject, string bodyText)
        {
            var message = new PostmarkMessage
            {
                From = from,
                To = to,
                Subject = subject,
                TextBody = bodyText,
                ReplyTo = "*****@*****.**"
            };

            var client = new PostmarkClient(_apiKey);
            var response = client.SendMessage(message);
        }
        protected override void ProcessRecord()
        {
            var message = new PostmarkMessage
            {
                From = From,
                To = To,
                Subject = Subject,
                HtmlBody = HtmlBody,
                TextBody = TextBody,
                ReplyTo = ReplyTo,
            };

            var response = PostmarkClient.SendMessage(message);
            WriteObject(response);
        }
        public void Can_generate_postmarkmessage_using_correct_tag_header_from_mailmessage()
        {
            var mm = new MailMessage
            {
                Subject = "test",
                Body = "test"
            };
            mm.To.Add("*****@*****.**");
            mm.Headers.Add("X-PM-Tag", "correct tag");
            //This header should be overridden by using the correct 'X-PM-Tag'
            mm.Headers.Add("X-PostmarkTag", "overridden tag");

            var pm = new PostmarkMessage(mm);
            Assert.AreEqual("correct tag", pm.Tag);
        }
Esempio n. 21
0
        private static void GetMailMessageTo(PostmarkMessage m, MailMessage message)
        {
            var sb = new StringBuilder(0);

            foreach (var to in message.To)
            {
                if (!string.IsNullOrEmpty(to.DisplayName))
                {
                    sb.AppendFormat("{0} <{1}>,", to.DisplayName, to.Address);
                }
                else
                {
                    sb.AppendFormat("{0},", to.Address);
                }
            }
            m.To = sb.ToString();
        }
Esempio n. 22
0
        private static void ValidatePostmarkMessage(PostmarkMessage message)
        {
            var specification = new ValidEmailSpecification();

            if (string.IsNullOrEmpty(message.From) || !specification.IsSatisfiedBy(message.From))
            {
                throw new ValidationException("You must specify a valid 'From' email address.");
            }
            if (!string.IsNullOrEmpty(message.To))
            {
                var recipients = message.To.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var recipient in recipients.Where(email => !specification.IsSatisfiedBy(email)))
                {
                    throw new ValidationException(
                              string.Format("The provided recipient address '{0}' is not valid", recipient)
                              );
                }
            }

            if (!string.IsNullOrEmpty(message.ReplyTo) && !specification.IsSatisfiedBy(message.ReplyTo))
            {
                throw new ValidationException("If a 'ReplyTo' email address is included, it must be valid.");
            }

            if (!string.IsNullOrEmpty(message.Cc))
            {
                var ccs = message.Cc.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var cc in ccs.Where(email => !specification.IsSatisfiedBy(email)))
                {
                    throw new ValidationException(
                              string.Format("The provided CC address '{0}' is not valid", cc)
                              );
                }
            }

            if (!string.IsNullOrEmpty(message.Bcc))
            {
                var bccs = message.Bcc.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var bcc in bccs.Where(email => !specification.IsSatisfiedBy(email)))
                {
                    throw new ValidationException(
                              string.Format("The provided BCC address '{0}' is not valid", bcc)
                              );
                }
            }
        }
Esempio n. 23
0
        public static PostmarkResponse SendEmail(string toAddress, string fromAddress, string subject, string body, string attachmentName = "", params File[] files)
        {
            string attachmentContent = null;
            if (files.Any())
            {
                try
                {
                    attachmentContent = ZipFiles(files);
                }
                catch (Exception ex)
                {
                    ErrorSignal.FromCurrentContext().Raise(new ApplicationException("Failed to zip email attachments.", ex));
                }
            }

            var message = new PostmarkMessage
                              {
                                  From = ConfigurationManager.AppSettings["PostmarkSignature"],
                                  ReplyTo = fromAddress,
                                  To = toAddress,
                                  Subject = subject,
                                  TextBody = body
                              };

            if (attachmentContent != null)
            {
                var attachment = new PostmarkMessageAttachment
                                     {
                                         Name = attachmentName + ".zip",
                                         ContentType = "application/zip",
                                         Content = attachmentContent
                                     };
                message.Attachments.Add(attachment);
            }

            var client = new PostmarkClient(ConfigurationManager.AppSettings["PostmarkApiKey"]);
            var result = client.SendMessage(message);

            if (result.Status != PostmarkStatus.Success)
            {
                ErrorSignal.FromCurrentContext().Raise(new ApplicationException(String.Format("Failed to send email to {0}.\nReason: {1}", toAddress, result.Message)));
            }
            return result;
        }
 private static PostmarkMessage CreatePostmarkMessage(EmailMessage message)
 {
     var pm = new PostmarkMessage
     {
         From = message.From,
         Subject = message.Subject,
         TextBody = message.TextBody,
         HtmlBody = message.HtmlBody,
         To = message.To.Count > 0 ? string.Join(",", message.To) : "",
         ReplyTo = message.ReplyTo.Count > 0 ? string.Join(",", message.ReplyTo) : "",
         Cc = message.Cc.Count > 0 ? string.Join(",", message.Cc) : "",
         Bcc = message.Bcc.Count > 0 ? string.Join(",", message.Bcc) : ""
     };
     foreach(var header in message.Headers)
     {
         pm.Headers.Add(header.Name, header.Value);
     }
     return pm;
 }
Esempio n. 25
0
        private static void GetHtmlBodyFromAlternateViews(PostmarkMessage m, MailMessage message)
        {
            if (message.AlternateViews.Count <= 0)
            {
                return;
            }

            var plainTextView = message.AlternateViews.Where(v => v.ContentType.MediaType.Equals(MediaTypeNames.Text.Plain)).FirstOrDefault();

            if (plainTextView != null)
            {
                m.TextBody = GetStringFromView(plainTextView);
            }

            var htmlView = message.AlternateViews.Where(v => v.ContentType.MediaType.Equals(MediaTypeNames.Text.Html)).FirstOrDefault();

            if (htmlView != null)
            {
                m.HtmlBody = GetStringFromView(htmlView);
            }
        }
        public void Can_send_message_with_token_and_signature_async()
        {
            var postmark = new PostmarkClient(_serverToken);

            var email = new PostmarkMessage
            {
                To = _to,
                From = _from, // This must be a verified sender signature
                Subject = Subject,
                TextBody = TextBody
            };

            var result = postmark.BeginSendMessage(email);
            var response = postmark.EndSendMessage(result);

            Assert.IsNotNull(response);
            Assert.IsNotNullOrEmpty(response.Message);
            Assert.IsTrue(response.Status == PostmarkStatus.Success);

            Console.WriteLine("Postmark -> {0}", response.Message);
        }
Esempio n. 27
0
        public ActionResult Contact(PostmarkMessage msg)
        {
            msg.From = "*****@*****.**";
            msg.To = "[email protected],[email protected]";

            return View("ThankYou");

            /*
            try
            {
                PostmarkClient client = new PostmarkClient("d5e6b4a6-5c98-4e63-a9ce-c22e6d5cdafc");
                PostmarkResponse response = client.SendMessage(msg);

                return View("ThankYou");
            }
            catch
            {
                return View("Contact", msg);
            }
            */
        }
        public void Can_send_message_with_CC_and_BCC()
        {
            var postmark = new PostmarkClient("POSTMARK_API_TEST");

            var email = new PostmarkMessage
                            {
                                To = _invalidRecipient,
                                Cc = "*****@*****.**",
                                Bcc = "*****@*****.**",
                                From = _invalidRecipient,
                                Subject = _subject,
                                TextBody = _textBody
                            };

            var response = postmark.SendMessage(email);

            Assert.IsNotNull(response);
            Assert.IsNotNullOrEmpty(response.Message);
            Assert.IsTrue(response.Status == PostmarkStatus.Success);

            Console.WriteLine("Postmark -> " + response.Message);
        }
        public void Can_send_message_without_token_and_receive_401()
        {
            var postmark = new PostmarkClient("");

            var email = new PostmarkMessage
                            {
                                To = _invalidRecipient,
                                From = _invalidRecipient,
                                Subject = _subject,
                                TextBody = _textBody
                            };

            var response = postmark.SendMessage(email);

            Assert.IsNotNull(response);
            Assert.IsNotNullOrEmpty(response.Message);
            Assert.IsTrue(response.Status == PostmarkStatus.UserError);

            Console.WriteLine("Postmark -> " + response.Message);
        }
        public void Can_send_message_without_signature_and_receive_422()
        {
            var postmark = new PostmarkClient(_serverToken);

            var email = new PostmarkMessage
                            {
                                To = _invalidRecipient,
                                From = _invalidRecipient, // This must not be a verified sender signature
                                Subject = _subject,
                                TextBody = _textBody
                            };

            var response = postmark.SendMessage(email);

            Assert.IsNotNull(response);
            Assert.IsNotNullOrEmpty(response.Message);
            Assert.IsTrue(response.Status == PostmarkStatus.UserError);

            Console.WriteLine("Postmark -> " + response.Message);
        }
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "from">An email address for a sender.</param>
        /// <param name = "to">An email address for a recipient.</param>
        /// <param name = "subject">The message subject line.</param>
        /// <param name = "textbody">The plain text body. Can be null if htmlbody is set.</param>
        /// <param name="htmlbody">The html text body. Can be null if textbody is set.</param>
        /// <param name = "headers">A collection of additional mail headers to send with the message.</param>
        /// <returns>A <see cref = "PostmarkResponse" /> with details about the transaction.</returns>
        public PostmarkResponse SendMessage(string from, string to, string subject, string textbody, string htmlbody, HeaderCollection headers)
        {
            var message = new PostmarkMessage(from, to, subject, textbody, htmlbody, headers);

            return(SendMessage(message));
        }
Esempio n. 32
0
        /// <summary>
        /// Sends a message through the Postmark API.
        /// All email addresses must be valid, and the sender must be
        /// a valid sender signature according to Postmark. To obtain a valid
        /// sender signature, log in to Postmark and navigate to:
        /// http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name="message">A prepared message instance.</param>
        /// <returns></returns>
        public PostmarkResponse SendMessage(PostmarkMessage message)
        {
            var request = NewEmailRequest();

            ValidatePostmarkMessage(message);
            CleanPostmarkMessage(message);

            request.Entity = message;

            return GetPostmarkResponse(request);
        }
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "from">An email address for a sender</param>
        /// <param name = "to">An email address for a recipient</param>
        /// <param name = "subject">The message subject line</param>
        /// <param name = "textBody">The plain text message body. This may be null, if htmlBody is set.</param>
        /// <param name = "htmlBody">The plain HTML message body. This may be null, if textBody is set.</param>
        /// <param name = "headers">A collection of additional mail headers to send with the message</param>
        /// <param name="callback">The callback invoked when a response is received from the API</param>
        /// <returns>A <see cref = "PostmarkResponse" /> with details about the transaction</returns>
        public void SendMessage(string from, string to, string subject, string textBody, string htmlBody, HeaderCollection headers, Action <PostmarkResponse> callback)
        {
            var message = new PostmarkMessage(from, to, subject, textBody, htmlBody, headers);

            SendMessage(message, callback);
        }
        public void Can_send_message_with_token_and_signature_and_name_based_email()
        {
            var postmark = new PostmarkClient(_serverToken);

            var email = new PostmarkMessage
            {
                To = _to,
                From = string.Format("The Team <{0}>", _from), // This must be a verified sender signature
                Subject = _subject,
                TextBody = _textBody
            };

            var response = postmark.SendMessage(email);

            Assert.IsNotNull(response);
            Assert.IsNotNullOrEmpty(response.Message);
            Assert.IsTrue(response.Status == PostmarkStatus.Success);

            Console.WriteLine("Postmark -> " + response.Message);
        }
Esempio n. 35
0
        public void SendPostMarkMail(string from, IEnumerable<string> to, string body, string subject, string postMarkToken, 
            IEnumerable<string> bcc = null, IEnumerable<string> cc = null,
            IEnumerable<MailAttachment> attachments = null)
        {
            var msg = new PostmarkMessage
            {
                From = from,
                To = String.Join(",", to),
                Bcc = bcc == null ? "" :  String.Join(",", bcc),
                 Cc = cc == null ? "" :  String.Join(",", cc),
                Subject = subject,
                HtmlBody = body,
                TextBody = body,
                Tag = subject
            };

            if (attachments != null)
            {
                if (attachments.Count() > 0)
                {
                    foreach (MailAttachment mailAttachment in attachments)
                    {
                        
                        msg.AddAttachment(mailAttachment.ByteArray, mailAttachment.ContentType.MediaType, mailAttachment.Name);
                    }

                }
            }
           

            var client = new PostmarkClient(postMarkToken);
            IAsyncResult result =  client.BeginSendMessage(msg);
            if (result.AsyncWaitHandle.WaitOne())
            {
                PostmarkResponse response = client.EndSendMessage(result);
            }
        }
Esempio n. 36
0
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "from">An email address for a sender</param>
        /// <param name = "to">An email address for a recipient</param>
        /// <param name = "subject">The message subject line</param>
        /// <param name = "body">The message body</param>
        /// <param name = "headers">A collection of additional mail headers to send with the message</param>
        /// <returns>A <see cref = "PostmarkResponse" /> with details about the transaction</returns>
        public IAsyncResult BeginSendMessage(string from, string to, string subject, string body, NameValueCollection headers)
        {
            var message = new PostmarkMessage(from, to, subject, body, headers);

            return(BeginSendMessage(message));
        }
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "from">An email address for a sender</param>
        /// <param name = "to">An email address for a recipient</param>
        /// <param name = "subject">The message subject line</param>
        /// <param name = "body">The message body</param>
        /// <param name = "headers">A collection of additional mail headers to send with the message</param>
        /// <param name="callback">The callback invoked when a response is received from the API</param>
        /// <returns>A <see cref = "PostmarkResponse" /> with details about the transaction</returns>
        public void SendMessage(string from, string to, string subject, string body, NameValueCollection headers, Action <PostmarkResponse> callback)
        {
            var message = new PostmarkMessage(from, to, subject, body, headers);

            SendMessage(message, callback);
        }
 private static void CleanPostmarkMessage(PostmarkMessage message)
 {
     message.From = message.From.Trim();
     if(!string.IsNullOrEmpty(message.To))
     {
         message.To = message.To.Trim();
     }
     message.Subject = message.Subject != null ? message.Subject.Trim() : "";
 }
Esempio n. 39
0
        /// <summary>
        /// Sends a message through the Postmark API.
        /// All email addresses must be valid, and the sender must be
        /// a valid sender signature according to Postmark. To obtain a valid
        /// sender signature, log in to Postmark and navigate to:
        /// http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name="from">An email address for a sender.</param>
        /// <param name="to">An email address for a recipient.</param>
        /// <param name="subject">The message subject line.</param>
        /// <param name="body">The message body.</param>
        /// <param name="headers">A collection of additional mail headers to send with the message.</param>
        /// <returns>A <see cref="PostmarkResponse"/> with details about the transaction.</returns>       
        public PostmarkResponse SendMessage(string from, string to, string subject, string body, NameValueCollection headers)
        {
            var message = new PostmarkMessage(from, to, subject, body, headers);

            return SendMessage(message);
        }
        public void Can_send_message_with_zipfile_attachment()
        {
            var postmark = new PostmarkClient(_serverToken);

            var email = new PostmarkMessage
            {
                To = _to,
                From = _from, // This must be a verified sender signature
                Subject = Subject,
                TextBody = TextBody,
                HtmlBody = HtmlBody
            };

            email.AddAttachment("zipfile.zip", "application/zip");

            var response = postmark.SendMessage(email);

            Assert.IsNotNull(response);
            Assert.IsNotNullOrEmpty(response.Message);
            Assert.IsTrue(response.Status == PostmarkStatus.Success);
            Console.WriteLine("Postmark -> {0}", response.Message);
        }
        public void Can_send_message_with_token_and_signature_and_headers()
        {
            var postmark = new PostmarkClient(_serverToken);

            var email = new PostmarkMessage
            {
                To = _to,
                From = _from, // This must be a verified sender signature
                Subject = _subject,
                TextBody = _textBody,
            };

            email.Headers.Add("X-Header-Test-1", "This is a header value");
            email.Headers.Add("X-Header-Test-2", "This is another header value");

            var response = postmark.SendMessage(email);

            Assert.IsNotNull(response);
            Assert.IsNotNullOrEmpty(response.Message);
            Assert.IsTrue(response.Status == PostmarkStatus.Success);
            Assert.AreNotEqual(default(DateTime), response.SubmittedAt, "Missing submitted time value.");

            Console.WriteLine("Postmark -> " + response.Message);
        }
Esempio n. 42
0
        /// <summary>
        ///   Initializes a new instance of the <see cref = "PostmarkMessage" /> class
        ///   based on an existing <see cref = "MailMessage" /> instance.
        ///
        ///   Only the first recipient of the message is added to the <see cref = "PostmarkMessage" />
        ///   instance.
        /// </summary>
        /// <param name = "message">The existing message.</param>
        private static PostmarkMessage ConvertSystemMailMessage(MailMessage message)
        {
            var pm = new PostmarkMessage();

            if (message.From != null)
            {
                pm.From = !string.IsNullOrEmpty(message.From.DisplayName)
                           ? string.Format("{0} <{1}>", message.From.DisplayName, message.From.Address)
                           : message.From.Address;
            }

            GetMailMessageRecipients(pm, message);

            pm.Subject  = message.Subject;
            pm.HtmlBody = message.IsBodyHtml ? message.Body : null;
            pm.TextBody = message.IsBodyHtml ? null : message.Body;

            GetHtmlBodyFromAlternateViews(pm, message);

            //Disabling "ReplyTo" obsolecense warning, as we need to continue to map this for users of the API that cannot upgrade."
#pragma warning disable 0618

            if (message.ReplyTo != null)
            {
                pm.ReplyTo = !string.IsNullOrEmpty(message.ReplyTo.DisplayName)
                              ? string.Format("{0} <{1}>", message.ReplyTo.DisplayName, message.ReplyTo.Address)
                              : message.ReplyTo.Address;
            }
#pragma warning restore 0618
            var header = message.Headers.Get("X-PostmarkTag");
            if (header != null)
            {
                pm.Tag = header;
            }

            pm.Headers = new HeaderCollection();

            if (message.Headers != null)
            {
                foreach (var h in message.Headers.AllKeys)
                {
                    pm.Headers.Add(h, message.Headers[h]);
                }
            }

            pm.Attachments = new List <PostmarkMessageAttachment>(0);

            foreach (var item in from attachment in message.Attachments
                     where attachment.ContentStream != null
                     let content = ReadStream(attachment.ContentStream, 8192)
                                   select new PostmarkMessageAttachment
            {
                Name = attachment.Name,
                ContentType = attachment.ContentType.ToString(),
                Content = Convert.ToBase64String(content)
            })
            {
                pm.Attachments.Add(item);
            }
            return(pm);
        }
        public void Can_send_message_with_token_and_signature_and_invalid_recipient_and_throw_validation_exception()
        {
            var postmark = new PostmarkClient(_serverToken);

            var email = new PostmarkMessage
                            {
                                To = "earth",
                                From = _from,
                                Subject = _subject,
                                TextBody = _textBody
                            };

            postmark.SendMessage(email);
        }
Esempio n. 44
0
 private static void GetMailMessageRecipients(PostmarkMessage m, MailMessage message)
 {
     GetMailMessageTo(m, message);
     GetMailMessageCc(m, message);
     GetMailMessageBcc(m, message);
 }
 private static bool IsBodyHtml(PostmarkMessage message)
 {
     return !string.IsNullOrEmpty(message.HtmlBody);
 }
Esempio n. 46
0
        /// <summary>
        ///   Sends a message through the Postmark API.
        ///   All email addresses must be valid, and the sender must be
        ///   a valid sender signature according to Postmark. To obtain a valid
        ///   sender signature, log in to Postmark and navigate to:
        ///   http://postmarkapp.com/signatures.
        /// </summary>
        /// <param name = "from">An email address for a sender</param>
        /// <param name = "to">An email address for a recipient</param>
        /// <param name = "subject">The message subject line</param>
        /// <param name = "textBody">The plain text message body. This may be null, if htmlBody is set.</param>
        /// <param name = "htmlBody">The plain HTML message body. This may be null, if textBody is set.</param>
        /// <param name = "headers">A collection of additional mail headers to send with the message</param>
        /// <returns>A <see cref = "PostmarkResponse" /> with details about the transaction</returns>
        public IAsyncResult BeginSendMessage(string from, string to, string subject, string textBody, string htmlBody, HeaderCollection headers)
        {
            var message = new PostmarkMessage(from, to, subject, textBody, htmlBody, headers);

            return(BeginSendMessage(message));
        }
Esempio n. 47
0
        private static void ValidatePostmarkMessage(PostmarkMessage message)
        {
            var specification = new ValidEmailSpecification();
            if (string.IsNullOrEmpty(message.From) || !specification.IsSatisfiedBy(message.From))
            {
                throw new ValidationException("You must specify a valid 'From' email address.");
            }
            if (string.IsNullOrEmpty(message.To))
            {
                throw new ValidationException("You must specify a valid 'To' email address.");
            }
            var recipients = message.To.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var recipient in recipients.Where(email => !specification.IsSatisfiedBy(email)))
            {
                throw new ValidationException(
                    string.Format("The provided recipient address '{0}' is not valid", recipient)
                    );
            }

            if (!string.IsNullOrEmpty(message.ReplyTo) && !specification.IsSatisfiedBy(message.ReplyTo))
            {
                throw new ValidationException("If a 'ReplyTo' email address is included, it must be valid.");
            }

            if(!string.IsNullOrEmpty(message.Cc))
            {
                var ccs = message.Cc.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var cc in ccs.Where(email => !specification.IsSatisfiedBy(email)))
                {
                    throw new ValidationException(
                        string.Format("The provided CC address '{0}' is not valid", cc)
                        );
                }
            }

            if (!string.IsNullOrEmpty(message.Bcc))
            {
                var bccs = message.Bcc.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var bcc in bccs.Where(email => !specification.IsSatisfiedBy(email)))
                {
                    throw new ValidationException(
                        string.Format("The provided BCC address '{0}' is not valid", bcc)
                        );
                }
            }
        }
Esempio n. 48
0
 private static void CleanPostmarkMessage(PostmarkMessage message)
 {
     message.From = message.From.Trim();
     message.To = message.To.Trim();
     message.Subject = message.Subject != null ? message.Subject.Trim() : "";
 }
Esempio n. 49
0
 /// <summary>
 /// Sends a message through the Postmark API.
 /// All email addresses must be valid, and the sender must be
 /// a valid sender signature according to Postmark. To obtain a valid
 /// sender signature, log in to Postmark and navigate to:
 /// http://postmarkapp.com/signatures.
 /// </summary>
 /// <param name="message">A prepared message.</param>
 /// <returns></returns>
 public async Task <PostmarkResponse> SendMessageAsync(PostmarkMessage message)
 {
     return(await ProcessRequestAsync <PostmarkMessage, PostmarkResponse>("/email", HttpMethod.Post, message));
 }
Esempio n. 50
0
        public void SendByApi()
        {
            PostmarkMessage message = new PostmarkMessage()
            {
                From = this.From
                , To = this.To
                , Cc = this.Cc
                , Bcc = this.Bcc
                ,Subject = this.Subject
                , ReplyTo = this.ReplyTo
            };

            if (this.IsBodyHtml)
                message.HtmlBody = this.Body;
            else
                message.TextBody = this.Body;

            if (this.Attachments != null && this.Attachments.Count > 0)
            {
                foreach (var attachment in this.Attachments)
                {
                    var bytes = new Byte[attachment.ContentStream.Length];
                    attachment.ContentStream.Read(bytes, 0, bytes.Length);
                    message.AddAttachment(bytes, attachment.ContentType.ToString(), attachment.Name);
                }
            }
            //Created just to get user name which will be used as ApiKey
            SmtpClient sc = new SmtpClient();
            PostmarkClient client = new PostmarkClient((sc.Credentials as NetworkCredential).UserName);
            var response = client.SendMessage(message);
            if (response.Status != PostmarkStatus.Success)
            {
                throw new System.Net.Mail.SmtpException(response.Message);
            }
        }