Skip to content

Email sending

Nick Hammond edited this page Sep 9, 2020 · 35 revisions

With Postmark you can send email messages very easy. Before diving into this chapter, make sure you have checked out our getting started page.

To send a simple email, all you need to do is create Postmark API client and send a mail message.

For these API requests you will need to use a server API token. Once you obtain it, you will need to use server API client.

server_token = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
client = Postmark::ApiClient.new(server_token, http_open_timeout: 15)

Sending a simple email

Check out the code below to see how to send a simple plain text email message.

client.deliver(from: 'sheldon@bigbangtheory.com',
               to: 'Leonard Hofstadter <leonard@bigbangtheory.com>',
               subject: 'Re: Come on, Sheldon. It will be fun.',
               text_body: 'That\'s what you said about the Green Lantern.')

# => {:to=>"Leonard Hofstadter <leonard@bigbangtheory.com>", :submitted_at=>"2013-05-09T02:45:16.2059023-04:00", :message_id=>"b2b268e3-6a70-xxxx-b897-49c9eb8b1d2e", :error_code=>0, :message=>"OK"}

Sending an email with tag

You can categorize outgoing email using the optional :tag property. If you use different tags for the different types of emails your application generates, you will be able to get detailed statistics for them through the Postmark user interface.

client.deliver(from: 'sheldon@bigbangtheory.com',
               to: 'Penny <penny@bigbangtheory.com>',
               subject: 'Re: You cleaned my apartment???',
               text_body: 'I couldn\'t sleep!',
               tag: 'confidential')

# => {:to=>"Penny <penny@bigbangtheory.com>", :submitted_at=>"2013-05-09T03:00:55.4454938-04:00", :message_id=>"34aed4b3-3a95-xxxx-bd1d-88064909cc93", :error_code=>0, :message=>"OK"}

Sending a simple email to custom message stream

Check out the code below to see how to send a simple plain text email message.

client.deliver(from: 'sheldon@bigbangtheory.com',
               to: 'Leonard Hofstadter <leonard@bigbangtheory.com>',
               subject: 'Re: Come on, Sheldon. It will be fun.',
               text_body: 'That\'s what you said about the Green Lantern.',
               message_stream: 'outbound'
)

# => {:to=>"Leonard Hofstadter <leonard@bigbangtheory.com>", :submitted_at=>"2013-05-09T02:45:16.2059023-04:00", :message_id=>"b2b268e3-6a70-xxxx-b897-49c9eb8b1d2e", :error_code=>0, :message=>"OK"}

Sending an email with custom headers

Check out the code below to see how to send a simple plain text email message.

client.deliver(from: 'sheldon@bigbangtheory.com',
               to: 'Leonard Hofstadter <leonard@bigbangtheory.com>',
               subject: 'Re: Come on, Sheldon. It will be fun.',
               text_body: 'That\'s what you said about the Green Lantern.',
               headers: [
                    {name: "Header1", value: "Value1"},
                    {name: 'Header2', value: 'Value2'}
                ])

# => {:to=>"Leonard Hofstadter <leonard@bigbangtheory.com>", :submitted_at=>"2019-05-09T02:45:16.2059023-04:00", :message_id=>"b21268e3-6a70-xxxx-b897-49c9eb8b1d2e", :error_code=>0, :message=>"OK"}

Sending a message with custom headers

message = Mail.new do
  from            'leonard@bigbangtheory.com'
  to              'Dr. Sheldon Cooper <sheldon@bigbangtheory.com>'
  subject         'Have you seen these pictures of yours?'
  body            'You look like a real geek!'
  add_file        '1.jpeg'

  delivery_method Mail::Postmark, :api_token => 'server token'
end

message['Header1'] = 'Value1'

message.deliver

# => #<Mail::Message:70185826686240, Multipart: true, Headers: <From: leonard@bigbangtheory.com>, <To: sheldon@bigbangtheory.com>, <Message-ID: b1644cc1-b5b1-4bcb-aaf8-2f290b5aad80>, <Subject: Have you seen these pictures of yours?>, <Content-Type: multipart/mixed; boundary=--==_mimepart_5121f9f1ec653_12c53fd569035ad817726>>

Sending a message with metadata

To send metadata with email messages you send, all you need to do is provide metadata for your messages in form of a hash map. Metadata can provide better and more advanced filtering and categorizing of your messages.

message = Mail.new do
  from            'leonard@bigbangtheory.com'
  to              'Dr. Sheldon Cooper <sheldon@bigbangtheory.com>'
  subject         'Have you seen these pictures of yours?'
  body            'You look like a real geek!'
  add_file        '1.jpeg'
  metadata        {"Example1"=>"value","Example2"=>"value"}

  delivery_method Mail::Postmark, :api_token => 'server token'
end

message.deliver

# => #<Mail::Message:70185826686240, Multipart: true, Headers: <From: leonard@bigbangtheory.com>, <To: sheldon@bigbangtheory.com>, <Message-ID: ba644cc1-b5b1-4bcb-aaf8-2f290b5aad80>, <Subject: Have you seen these pictures of yours?>, <Content-Type: multipart/mixed; boundary=--==_mimepart_5121f9f1ec653_12c53fd569035ad817726>>

Please notice that in this case Mail library was used to compose the message. To find out more about this feature, check out the following guide.

Sending a message with open tracking enabled

Simply pass an HTML document as html_body parameter to #deliver. You can also enable open tracking by setting track_opens to true.

client.deliver(from: 'sheldon@bigbangtheory.com',
               to: 'Leonard Hofstadter <leonard@bigbangtheory.com>',
               subject: 'Re: What, to you, is a large crowd?',
               html_body: '<p>Any group big enough to trample me to death. ' \
                          'General rule of thumb is 36 adults or 70 ' \
                          'children.</p>',
               track_opens: true)

# => {:to=>"Leonard Hofstadter <leonard@bigbangtheory.com>", :submitted_at=>"2013-05-09T02:51:08.8789433-04:00", :message_id=>"75c28987-564e-xxxx-b6eb-e8071873ac06", :error_code=>0, :message=>"OK"}

Sending a message with link tracking enabled

To track visited links for emails you send, make sure to have links in html body, text body or both of the email you plan to send. You need to enable link tracking by setting track_links parameter to one of the following options: :html_only, :text_only, :html_and_text or :none.

Depending on parameter you set, link tracking will be enabled on plain text body, html body, both or none. Optionally you can also use string values as parameters 'HtmlOnly', 'TextOnly', 'HtmlAndText' or 'None'.

Notice that we set track_links field to :html_and_text, to enable link tracking for both plain text and html parts for this message.

message = Mail.new do
  from            'sheldon@bigbangtheory.com'
  to              'Leonard Hofstadter <leonard@bigbangtheory.com>'
  subject         'Re: What, to you, is a large crowd?'

  text_part do
    body          'Any group big enough to trample me to death. General rule of thumb is 36 adults or 70 children - http://www.example.com.'
  end

  html_part do
    content_type  'text/html; charset=UTF-8'
    body          '<p>Any group big enough to trample me to death. ' \
                  'General <a href="http://www.example.com">rule of thumb</a> is 36 adults or 70 ' \
                  'children.</p>'
  end

  track_links     :html_and_text

  delivery_method Mail::Postmark, :api_token => 'server token'
end

message.deliver

# => #<Mail::Message:70355902117460, Multipart: true, Headers: <From: sheldon@bigbangtheory.com>, <To: leonard@bigbangtheory.com>, <Message-ID: 1a1370a1-6c21-4304-a03c-320a54cc59f7>, <Subject: Re: What, to you, is a large crowd?>, <Content-Type: multipart/alternative; boundary=--==_mimepart_58380d6029b17_20543fd48543fa14977a>, <TRACK-LINKS: HtmlAndText>>

Sending a message with attachments

You can add attachments to messages you send. Keep in mind attachment size is limited to 10Mb.

message = Mail.new do
  from            'leonard@bigbangtheory.com'
  to              'Dr. Sheldon Cooper <sheldon@bigbangtheory.com>'
  subject         'Have you seen these pictures of yours?'
  body            'You look like a real geek!'

  delivery_method Mail::Postmark, :api_token => 'server token'
end

message.attachments['sheldon.jpeg'] = File.read('2.jpeg')
message.deliver

# => #<Mail::Message:70185826686240, Multipart: true, Headers: <From: leonard@bigbangtheory.com>, <To: sheldon@bigbangtheory.com>, <Message-ID: ba644cc1-b5b1-4bcb-aaf8-2f290b5aad80>, <Subject: Have you seen these pictures of yours?>, <Content-Type: multipart/mixed; boundary=--==_mimepart_5121f9f1ec653_12c53fd569035ad817726>>

You can also make an attachment inline:

message.attachments.inline['sheldon.jpeg'] = File.read('2.jpeg')

Then simply use Mail::Part#url method to reference it from your email body.

<p><img src="<%= message.attachments['sheldon.jpeg'].url %>" alt="Dr. Sheldon Cooper"></p>

For inline attachments it is possible to specify content IDs via the content_id attribute.

client.deliver(from: 'leonard@bigbangtheory.com',
               to: 'Dr. Sheldon Cooper <sheldon@bigbangtheory.com>',
               subject: 'Have you seen these pictures of yours?',
               text_body: 'You look like a real geek!',
               html_body: '<p>You look like a real geek!</p><center><img src="cid:42"></center>',
               attachments: [File.open('1.jpeg'),
                             {name: 'sheldon.jpeg',
                              content: [File.read('2.jpeg')].pack('m'),
                              content_type: 'image/jpeg'},
                             {name: 'logo.png',
                              content: [File.read('1.png')].pack('m'),
                              content_type: 'image/png',
                              content_id: 'cid:42'}])

# => {:to=>"Dr. Sheldon Cooper <sheldon@bigbangtheory.com>", :submitted_at=>"2013-05-09T02:56:12.2828813-04:00", :message_id=>"8ec0d283-8b93-xxxx-9d65-241d1777cf0f", :error_code=>0, :message=>"OK"}

Sending a multipart message

client.deliver(from: 'sheldon@bigbangtheory.com',
               to: 'Leonard Hofstadter <leonard@bigbangtheory.com>',
               subject: 'Re: Anything Can Happen Thursday',
               text_body: 'Apparently the news didn\'t reach my digestive ' \
                          'system, which when startled has it\'s own version ' \
                          'of "Anything Can Happen Thursday"',
               html_body: '<p>Apparently the news didn&rsquo;t reach my ' \
                          'digestive system, which when startled has ' \
                          'it&rsquo;s own version of &ldquo;Anything Can '\
                          'Happen Thursday&rdquo;</p>')

# => {:to=>"Leonard Hofstadter <leonard@bigbangtheory.com>", :submitted_at=>"2013-05-09T02:58:00.089828-04:00", :message_id=>"bc973458-1315-xxxx-b295-6aa0a2b631ac", :error_code=>0, :message=>"OK"}

Sending to multiple recipients

You can pass multiple recipient addresses in the :to field and the optional :cc and :bcc fields. Note that Postmark has a limit of 50 recipients per message in total. You need to take care not to exceed that limit. Otherwise, you will get an error.

client.deliver(from: 'sheldon@bigbangtheory.com',
               to: ['Leonard Hofstadter <leonard@bigbangtheory.com>',
                    'Penny <penny@bigbangtheory.com>'],
               cc: ['Dr. Koothrappali <raj@bigbangtheory.com>'],
               bcc: 'secretsheldonstorage@bigbangtheory.com',
               subject: 'Re: Come on, Sheldon. It will be fun.',
               text_body: 'That\'s what you said about the Green Lantern ' \
                          'movie. You were 114 minutes of wrong.')

# => {:to=>"Leonard Hofstadter <leonard@bigbangtheory.com>, Penny <penny@bigbangtheory.com>", :submitted_at=>"2013-05-09T05:04:16.3247488-04:00", :message_id=>"d647c5d6-xxxx-466d-9411-557dcd5c2297", :error_code=>0, :message=>"OK"}

Deliver email in batches

Sometimes you would like to send many emails at once. Postmark allows you to do that by sending array of emails in batches. In order to do that, check out the following code example:

messages = []

messages << {from: 'sheldon@bigbangtheory.com',
             to: 'Leonard Hofstadter <leonard@bigbangtheory.com>',
             subject: 'Re: Come on, Sheldon. It will be fun.',
             text_body: 'That\'s what you said about the Green Lantern ' \
                        'movie. You were 114 minutes of wrong.'}

messages << {from: 'sheldon@bigbangtheory.com',
             to: 'Penny <penny@bigbangtheory.com>',
             subject: 'Re: You cleaned my apartment???',
             text_body: 'I couldn\'t sleep knowing that just outside my ' \
                        'bedroom is our living room and just outside our ' \
                        'living room is that hallway and immediately ' \
                        'adjacent to that hallway is this!',
             tag: 'confidential'}

response = client.deliver_in_batches(messages)

# => [{:to=>"Leonard Hofstadter <leonard@bigbangtheory.com>", :submitted_at=>"2013-05-09T05:19:16.3361118-04:00", :message_id=>"247e43a9-6b0d-4914-a87f-7b74bf76b5cb", :error_code=>0, :message=>"OK"}, {:to=>"Penny <penny@bigbangtheory.com>", :submitted_at=>"2013-05-09T05:19:16.3517099-04:00", :message_id=>"26467642-f169-4da8-87a8-b89154067dfb", :error_code=>0, :message=>"OK"}]

After delivering a batch you can check on each message’s delivery status:

response.first.delivered?
# => true

response.all?(&:delivered)
# => true

Please note that the delivering email in batches will return a 200-level HTTP status, even when validation for individual messages may fail - like bounced messages. Users of this endpoint should check the response for each message in the response from our API.

Clone this wiki locally