Send email with attachment in Ruby Send email with attachment in Ruby ruby ruby

Send email with attachment in Ruby


Have you checked out Mail? That is what the new ActionMailer API in Rails 3 is built upon.

"Mail is an internet library for Ruby that is designed to handle emails generation, parsing and sending in a simple, rubyesque manner."

Here comes a quick example from the docs:

require 'mail'@mail = Mail.newfile_data = File.read('path/to/myfile.pdf')@mail.attachments['myfile.pdf'] = { :mime_type => 'application/x-pdf',                                    :content => file_data }

Update: Or even more simply:

@mail = Mail.new@mail.add_file("/path/to/file.jpg")


Sending Email or Email with any type of attachment has become more simple with the "mail" gem installation.

Step:1 Install "mail" gem

Step:2 In the ruby file maintain the syntax given below:

require 'mail'def mailsender      Mail.defaults do        delivery_method :smtp,{ address: "<smtp_address>",openssl_verify_mode: "none" }      end      Mail.deliver do        from     'from_mail_id'        to       'to_mail_id'        subject  'subject_to_be_sent'        # body     File.read('body.txt')        body     'body.txt'        add_file '<file_location>/Word Doc.docx'        add_file '<file_location>/Word Doc.doc'      endend

Step:3 now Just call the method in the step definition.


Full documentation: here

require 'mail'Mail.deliver do  from      "bob@example.com"  to        "alice@example.com"  subject   "Email with attachment"  body      "Hello world"  add_file  "/path/to/file"end