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 = <
To: RECEIVER
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', '[email protected]', 'PASSWORD', :login)
smtp.send_message message, '[email protected]', '[email protected]'
smtp.finish
#Using Block
smtp = Net::SMTP.new('smtp.gmail.com', 587 )
smtp.enable_starttls
smtp.start('gmail.com', '[email protected]', 'PASSWORD', :login) do |smtp|
smtp.send_message message, '[email protected]', '[email protected]'
end
Hope it helps! ๐
Yes, you can.
Add this line before subject:
Example:
Hi,
If I also want to send images or link certain words on my email template, how would I do so in your format?
Ok. Good to know that. ๐
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.
No, it won’t. I have tested it.
this send an email, but send me an empty email ๐
Simple script, that does all required.
Thanks a bunch!!! worked like a charm!!!
Awesome script!!!
Thank you very much!!!