Ruby: Sending mails via Gmail SMTP with authentication

On September 15, 2012, in Ruby, by Dipin Krishna

This is a tutorial on how to send mails via Gmail SMTP using ruby.
Here, we are going to use the Net::SMTP library for this. This library provides functionality to send internet mail via SMTP.

How it works:

  1. Create a new Net::SMTP object.

     smtp = Net::SMTP.new 'smtp.gmail.com', 587
  2. Enable TLS.

     smtp.enable_starttls
  3. Create an SMTP connection to the server and authenticate.

     smtp.start('gmail.com', 'USERNAME', 'PASSWORD', :login)

    If called with a block, the newly-opened Net::SMTP object is yielded to the block, and automatically closed when the block finishes.

     smtp.start('gmail.com', 'USERNAME','PASSWORD', :login) do |smtp|
    	......
     end

    If called without a block, the newly-opened Net::SMTP object is returned to the caller, and it is the callerโ€™s responsibility to close it when finished.

     smtp.start('gmail.com', 'USERNAME', 'PASSWORD', :login)
     ......
     smtp.finish
  4. Send Message

     smtp.send_message "Message", 'SENDER', 'RECEIVER'

Below is a sample script:

require 'net/smtp'
 
message = <<EOF
From: SENDER <FROM@gmail.com>
To: RECEIVER <TO@gmail.com>
Subject: SMTP Test E-mail
This is a test message.
EOF
 
smtp = Net::SMTP.new 'smtp.gmail.com', 587
smtp.enable_starttls
smtp.start('gmail.com', 'username@gmail.com', 'PASSWORD', :login)
smtp.send_message message, 'FROM@gmail.com', 'TO@gmail.com'
smtp.finish
 
#Using Block
smtp = Net::SMTP.new('smtp.gmail.com', 587 )
smtp.enable_starttls
smtp.start('gmail.com', 'username@gmail.com', 'PASSWORD', :login) do |smtp|
        smtp.send_message message, 'FROM@gmail.com', 'TO@gmail.com'
end

Hope it helps! ๐Ÿ™‚

Tagged with:  

9 Responses to “Ruby: Sending mails via Gmail SMTP with authentication”

  1. Marco Lau says:

    Hi,

    If I also want to send images or link certain words on my email template, how would I do so in your format?

    • Yes, you can.
      Add this line before subject:

      Content-Type: text/html; charset=us-ascii;

      Example:

      From: SENDER <mail@dipinkrishna.com>
      To: RECEIVER <mail@dipinkrishna.com>
      Content-Type: text/html; charset=us-ascii;
      Subject: SMTP Test E-mail
      This is a test <a href="dipinkrishna.com" rel="nofollow">link</a>.
      <img src="https://dipinkrishna.com/mylogo.png"/>
  2. Joseph says:

    this send an email, but send me an empty email ๐Ÿ™

  3. Buminda says:

    Simple script, that does all required.

  4. Joseph says:

    Thanks a bunch!!! worked like a charm!!!

  5. amerem says:

    Awesome script!!!
    Thank you very much!!!

Leave a Reply

*

Search