Site icon Dipin Krishna

Ruby: Sending mails via Gmail SMTP with authentication

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! 🙂

Exit mobile version