SendMessage() public method

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.
public SendMessage ( PostmarkMessage message ) : PostmarkResponse
message PostmarkMessage A prepared message instance.
return PostmarkResponse
Example #1
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 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);
        }
        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);
        }
        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);
        }
        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);
        }
Example #8
0
        public String SendInvoiceEmail(string sendTo, string ccEmails, string fromEmail, string organizationName,
                           string invoicURL, string fileName, string paymentURL, string invoiceNumber,
                           string invoicePath, string postMarkAPIKey)
        {
            string returnMessage = string.Empty;

             // Build the message
             StringBuilder oSB = new StringBuilder();
             oSB.AppendLine(string.Format("{0},", organizationName));
             oSB.AppendLine("<br/>");
             oSB.AppendLine("<br/>");
             oSB.AppendLine(string.Format("Your monthly invoice is attached. You may <a href='{0}{1}'>view it here</a>.<br/>", invoicURL, fileName));
             oSB.AppendLine("<br/>");
             oSB.AppendLine("Please pay special attention to the Balance Due at the bottom of the invoice. If any prepayments or credits have been applied to this invoice then the Balance Due will not be the same as the Invoice Total. Please pay the Balance Due.<br/>");
             oSB.AppendLine(string.Format("To make a payment <a href='{0}?i={1}'>click here</a>.<br/>", paymentURL, invoiceNumber));
             oSB.AppendLine("<br/>");
             oSB.AppendLine("Thank you for your business – we appreciate it very much.<br/>");
             oSB.AppendLine("<br/>");
             oSB.AppendLine("Sincerely,<br/>");
             oSB.AppendLine("<br/>");
             oSB.AppendLine("Rhonda Ball<br/>");
             oSB.AppendLine("Accounting Office Manager<br/>");
             oSB.AppendLine("Speedy Spots, Inc.<br/>");
             oSB.AppendLine("734-475-9327<br/>");
             oSB.AppendLine("734-475-4645 fax<br/><br/>");
             oSB.AppendLine("**All accounts that have an invoice 60 days past due will be put on Prepay status**<br/>");
             string finalBody = oSB.ToString();

             // Attachment
             string fullInvoicePath = Path.Combine(invoicePath, fileName);
             string subject = "Invoice Ready";
             string postMarkServerTokenDesc = "X-Postmark-Server-Token";

             // Build the email
             try
             {

            PostmarkMessage newMessage = new PostmarkMessage
            {
               From = fromEmail,
               To = sendTo,
               Cc = ccEmails,
               Subject = subject,
               HtmlBody = finalBody,
               TextBody = string.Empty,
               ReplyTo = fromEmail,
               Headers = new NameValueCollection { { postMarkServerTokenDesc, postMarkAPIKey } }
            };

            newMessage.AddAttachment(fullInvoicePath, "application/pdf");

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

            if (response.Status != PostmarkStatus.Success)
            {
               returnMessage = response.Message;
            }
            else
            {
               returnMessage = response.ErrorCode.ToString();
            }

            _postmarkCode = response.ErrorCode.ToString();
            _postmarkStatus = response.Status.ToString();
            _postmarkMessage = response.Message.ToString();
            _postmarkMessageID = response.MessageID.ToString();
            _postmarkSubmittedAt = (response.SubmittedAt > DateTime.MinValue) ? response.SubmittedAt : new DateTime(1950, 1, 1);
             }
             catch (PostmarkDotNet.Validation.ValidationException exPM)
             {
            _logger.ErrorFormat("Postmark validation exception while sending invoice email: {0}", exPM.Message);
            returnMessage = exPM.Message;

            _postmarkCode = "ValidationException";
            _postmarkStatus = "PostMarkError";
            _postmarkMessage = exPM.Message;
            _postmarkMessageID = Guid.Empty.ToString();
            _postmarkSubmittedAt = new DateTime(1950, 1, 1);
             }
             catch (Exception ex)
             {
            _logger.ErrorFormat("PM exception while sending invoice email: {0}", ex.Message);
            returnMessage = ex.Message;

            _postmarkCode = "GeneralException";
            _postmarkStatus = "PostMarkError";
            _postmarkMessage = ex.Message;
            _postmarkMessageID = Guid.Empty.ToString();
            _postmarkSubmittedAt = new DateTime(1950, 1, 1);
             }

             return returnMessage;
        }
        public void Can_send_message_with_token_and_signature()
        {
            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 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_with_file_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,
            };

            email.AddAttachment("logo.png", "image/png");

            var response = postmark.SendMessage(email);

            Assert.IsNotNull(response);
            Assert.IsNotNullOrEmpty(response.Message);
            Assert.IsTrue(response.Status == PostmarkStatus.Success);
            Console.WriteLine("Postmark -> " + response.Message);
        }
Example #11
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;
        }
Example #12
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;
        }
Example #13
0
        public string SendSummaryEmail(string sendTo, string emailFrom, string arriveDateTime, string processTimeMinutes,
            string invoiceCountReceived, string invoicesCountProcessed, string invoiceEmailsSentCount, int invoiceEmailsSkippedCount, string invoiceEmailErrorInformation,
            string postMarkAPIKey)
        {
            _logger.DebugFormat("Sending summary email to: {0}", sendTo);

             string returnMessage = string.Empty;

             // Build the message
             StringBuilder oSB = new StringBuilder();
             oSB.AppendLine("The invoice package for " + arriveDateTime + " has completed and took " + processTimeMinutes);
             oSB.AppendLine(" minute(s).");
             oSB.AppendLine("<br/>");
             oSB.AppendLine("<br/>");
             oSB.AppendLine("Invoices Received:  " + invoiceCountReceived);
             oSB.AppendLine("<br/>");
             oSB.AppendLine("Invoices Processed:  " + invoicesCountProcessed);
             oSB.AppendLine("<br/>");
             oSB.AppendLine("Invoice Emails Sent:  " + invoiceEmailsSentCount);
             oSB.AppendLine("<br/>");
             if (invoiceEmailsSkippedCount > 0)
             {
            oSB.AppendLine("Invoice Emails Skipped: " + invoiceEmailsSkippedCount.ToString());
            oSB.AppendLine("<br/>");
             }
             oSB.AppendLine("Invoice Email Errors: ");
             oSB.AppendLine("<br/>");
             oSB.AppendLine("<br/>");
             oSB.AppendLine(invoiceEmailErrorInformation);

             string finalBody = oSB.ToString();

             string emailSubject = "Invoice Package Report for " + Convert.ToDateTime(arriveDateTime).ToString("M/d/yyyy");
             string postMarkServerTokenDesc = "X-Postmark-Server-Token";

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

            PostmarkMessage newMessage = new PostmarkMessage
            {
               From = emailFrom,
               To = sendTo,
               Subject = emailSubject,
               HtmlBody = finalBody,
               TextBody = string.Empty,
               ReplyTo = emailFrom,
               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 report: {0}", returnMessage);
             }
             catch (Exception ex)
             {
            returnMessage = ex.ToString();
            _logger.ErrorFormat("Exception sending report: {0}", returnMessage);
             }

             return returnMessage;
        }
        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);
        }
        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);
            }
        }
        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);
        }
Example #17
0
        public string SendInvoiceEmail(string sendTo, string ccEmails, string fromEmail, string organizationName,
                           string invoicURL, string fileName, string paymentURL, string invoiceNumber,
                           string invoicePath, string postMarkAPIKey, string subject, string body)
        {
            string returnMessage = string.Empty;

             // Attachment
             string fullInvoicePath = Path.Combine(invoicePath, fileName);
             string postMarkServerTokenDesc = "X-Postmark-Server-Token";

             // Build the email
             try
             {
            PostmarkMessage newMessage = new PostmarkMessage
            {
               From = fromEmail,
               To = sendTo,
               Cc = ccEmails,
               Subject = subject,
               HtmlBody = body,
               TextBody = string.Empty,
               ReplyTo = fromEmail,
               Headers = new NameValueCollection { { postMarkServerTokenDesc, postMarkAPIKey } }
            };

            newMessage.AddAttachment(fullInvoicePath, "application/pdf");

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

            if (response.Status != PostmarkStatus.Success)
            {
               returnMessage = response.Message;
            }
            else
            {
               returnMessage = response.ErrorCode.ToString();
            }

            _postmarkCode = response.ErrorCode.ToString();
            _postmarkStatus = response.Status.ToString();
            _postmarkMessage = response.Message.ToString();
            _postmarkMessageID = response.MessageID.ToString();
            _postmarkSubmittedAt = (response.SubmittedAt > DateTime.MinValue) ? response.SubmittedAt : new DateTime(1950, 1, 1);
             }
             catch (PostmarkDotNet.Validation.ValidationException exPM)
             {
            _logger.ErrorFormat("Postmark validation exception while sending invoice email: {0}", exPM.Message);
            returnMessage = exPM.Message;

            _postmarkCode = "ValidationException";
            _postmarkStatus = "PostMarkError";
            _postmarkMessage = exPM.Message;
            _postmarkMessageID = Guid.Empty.ToString();
            _postmarkSubmittedAt = new DateTime(1950, 1, 1);
             }
             catch (Exception ex)
             {
            _logger.ErrorFormat("PM exception while sending invoice email: {0}", ex.Message);
            returnMessage = ex.Message;

            _postmarkCode = "GeneralException";
            _postmarkStatus = "PostMarkError";
            _postmarkMessage = ex.Message;
            _postmarkMessageID = Guid.Empty.ToString();
            _postmarkSubmittedAt = new DateTime(1950, 1, 1);
             }

             return returnMessage;
        }