Send email with attachment in Ruby
Asked Answered
M

3

14

I need to send an email with an attachment via Ruby.

Been searching around but haven't found any simple script example to do this.

Closest I've found is ActionMailer but that seems to require a bunch of other scripts to to run. (NOTE: I am not using Ruby on Rails)

Marshall answered 7/7, 2010 at 13:24 Comment(0)
T
18

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.new
file_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")
Telecast answered 7/7, 2010 at 13:33 Comment(2)
@sergiovilar: Mail is a pure Ruby library. It does not depend on Rails. Hence it is a valid answer (even today, 6 years after the answer was posted).Telecast
I am getting this error: undefined method '[]' for nil:NilClassOjeda
P
2

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'
      end
end

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

Prodigious answered 31/8, 2017 at 7:58 Comment(0)
H
1

Full documentation: here

require 'mail'

Mail.deliver do
  from      "[email protected]"
  to        "[email protected]"
  subject   "Email with attachment"
  body      "Hello world"
  add_file  "/path/to/file"
end
Hereford answered 22/3, 2015 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.