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! ๐Ÿ™‚

Comments (9)

  1. 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. Marco Lau

    Hi,

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

  3. Joseph

    I figured out why doesn’t send the email, I try to send a date like this:

    YYYY-MM-DD HH:MM:SS

    The “:” send me an empty mail, maybe is the codification.

Leave a comment

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.