I came across a rather interesting discovery today that email is quite simple to send within Ruby. Check it out:
Simple Email
require 'net/smtp'
message = 'Hello Dude'
Net::SMTP.start('127.0.0.1',25) do |smtp|
smtp.send_message(message, 'from@from.com','to@to.com')
end
Granted, this is a very simple example, but the principles are still there. Write a message as a string, start a new SMTP connection, tell it where it’s from and going, and send it on its way.
The problem with this method is that you wind up with some very ugly(nonexistent) headers that spam catchers may not like. One way around this is to include them in the message as follows:
Simple Email with Headers
require 'net/smtp'
message = <<MESSAGE_END
From: test@hello.com
To: to@to.com
Subject: Sample Message
Hello, this is a message
MESSAGE_END
p message
Net::SMTP.start('10.245.27.10',25,'localhost') do |smtp|
smtp.send_message(message, 'test@hello.com','to@to.com')
end
This gives you greater control over the headers. However, I still found this to be a bother for the simple sake of having to type the to field multiple times. That’s the sort of thing that can lead to errors in code (it actually messed me up for a a minute while writing this). So my last bit moves the message into class form, allowing us to keep our sending portion short, clean, and less error prone. This involves two files, emailMessage.rb and email.rb. They are shown below:
emailMessage.rb
class EmailMessage
attr_accessor :to
attr_accessor :from
attr_accessor :message
attr_accessor :subject
def initialize(attributes)
@to = attributes[:to]
@from = attributes[:from]
@message = attributes[:message]
@subject = attributes[:subject]
end
def to_s
<<MESSAGE_END
From: #{@from}
To: #{@to}
Subject: #{@subject}
#{@message}
MESSAGE_END
end
end
email.rb
require 'net/smtp'
require 'emailMessage'
em = EmailMessage.new :to=>;'to@to.com', :from=>;'test@test.com', :subject=>;'mysubject'
em.message = 'This is the message'
Net::SMTP.start('127.0.0.1',25) do |smtp|
smtp.send_message(em.to_s, em.from,em.to)
end
We’re back to a short, clean, email.rb that can be used for sending email with most SMTP.
Using SSL
Some SMTP hosts, including Gmail, requires the usage of SSL to send emails. This is not built into the standard Ruby libraries. However, Stephen Chu has a great post covering how to do it in Ruby.