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:
- Create a new Net::SMTP object.
smtp = Net::SMTP.new 'smtp.gmail.com', 587
- Enable TLS.
smtp.enable_starttls
- 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
- 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! 🙂