Friday, March 15, 2013

Ruby on Rails, Sending mails easily using pony gem

Send mails easily using pony gem (Ruby on Rails)

How to install the gem?

Shell=> gem install pony

If you have a rails app then put the following in your Gemfile and run bundle

gem 'pony'

Shell => bundle

Then open up irb

require 'rubygems'
require 'pony'

Pony.mail(:to=>'test@test.com', :from => 'foo@bar.com')

If you have sendmail configured then pony will use sendmail to relay your mails by default.


Pony.mail({
  :to => 'you@example.com',
  :via => :sendmail,
  :via_options => {
    :location  => '/path/to/sendmail', # defaults to 'which sendmail' or '/usr/sbin/sendmail' if 'which' fails
    :arguments => '-t' # -t and -i are the defaults
  }
})


You can also configure postfix to relay mails to your smtp server, you will find more information HERE 

or you can give the smtp configuration in pony directly.


Pony.mail({
  :to => 'you@example.com',
  :via => :smtp,
  :via_options => {
    :address        => 'smtp.yourserver.com',
    :port           => '25',
    :user_name      => 'user',
    :password       => 'password',
    :authentication => :plain, # :plain, :login, :cram_md5, no auth by default
    :domain         => "localhost.localdomain" # the HELO domain provided by the client to the server
  }
})



Pony.mail({
  :to => 'you@example.com',
  :via => :smtp,
  :via_options => {
    :address              => 'smtp.gmail.com',
    :port                 => '587',
    :enable_starttls_auto => true,
    :user_name            => 'user',
    :password             => 'password',
    :authentication       => :plain, # :plain, :login, :cram_md5, no auth by default
    :domain               => "localhost.localdomain" # the HELO domain provided by the client to the server
  }
})

Attachments

You can attach a file or two with the :attachments option:
Pony.mail(..., :attachments => {"foo.zip" => File.read("path/to/foo.zip"), "hello.txt" => "hello!"})

Custom Headers

Pony allows you to specify custom mail headers
Pony.mail(
  :to => 'me@example.com',
  :headers => { "List-ID" => "...", "X-My-Custom-Header" => "what a cool custom header" }
)

List Of Options

Options passed pretty much directly to Mail
to
cc
bcc
from
body # the plain text body
html_body # for sending html-formatted email
subject
charset # In case you need to send in utf-8 or similar
text_part_charset # for multipart messages, set the charset of the text part
attachments # see Attachments section above
headers # see Custom headers section above
message_id
sender  # Sets "envelope from" (and the Sender header)
reply_to
Further Readings:
https://github.com/benprew/pony