/ rails

send email attachments via postmark-api

Previously, I have added post on send email from application via postmark. [Check Here..][1]

Now will see how to send attachment with email.

  1. In rails, action-mailer provides an easy way to add attachment file as
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')

Links: [rails-guide-on-attchments(send attachments with email)][2] , [rails-attachments][3]

  1. Sending attachments via Postmark-api
require "open-uri"

def send_refer_pt_request(params, attachment)
    # attachment -> url of file saved on S3
    if attachment.present?
      mime_type = MIME::Types.type_for(attachment).first
      url_data  = open(attachment).read()
      attachments["#{attachment.split('/').last}"] = { mime_type: mime_type,
        content: url_data }
      from:     ,
      to:       ,
      subject:  "Refer Request",
      tag:      "refer_request")

Few Points to make sure while sending attachments:

  1. Previously, Postmark was not supporting attachments, so make sure that in your application you are using latest version of Postmark-rails gem.

Links: [Postmark-Blog][4] , [postmark-rails-gem][5]

Because, if you are using an old version of this gem, then it will send email without attachment but would not show any exception or any error for attachment not being sent , it would just exclude your attachment files.

gem ‘postmark-rails’, “~> 0.5.2”
  1. Attachment size can be 10 MB at most.

  2. Only allowed file types can be sent as attachments. [Supported-File-Types][6]

  3. If you want to send a file from remote url, then you need to read that file before you add it as attachment.

require "open-uri"
mime_type                   = MIME::Types.type_for(attachment).first
url_data                    = open(attachment_url).read()
attachments["#{file_name}"] = { mime_type: mime_type, content: url_data }
  1. Also it is recommended by Postmark, that if you want to send email with attachments, send your email from background job. [Check Here..][7]
    [1]: http://knowbuddy.kiprosh-app.com/kyu_entries/send-email-from-application-via-postmark
    [2]: http://guides.rubyonrails.org/action_mailer_basics.html#complete-list-of-action-mailer-methods
    [3]: http://api.rubyonrails.org/classes/ActionMailer/Base.html#label-Attachments
    [4]: http://blog.postmarkapp.com/post/927675495/attachments-finally-here
    [5]: https://github.com/wildbit/postmark-rails/issues/25
    [6]: http://developer.postmarkapp.com/developer-build.html#attachments
    [7]: http://blog.postmarkapp.com/post/927675495/attachments-finally-here

Swati Jadhav

I am a Rubyist, ROR developer, passionate about change and trying new things, both professionally and in general with life. Currently, working on Ember.js applications and fasci...

Read More