class EZ::Email
The Email
class encapsulates certain SMTP attributes, which are then used to send simple emails.
Constants
- VERSION
The version of the ez-email library
Attributes
The body of the email. Mandatory.
A single email address from whom the email is being delivered. The default is your login + '@' + your host name, though it is recommended that you specify it explicitly.
The subject of the email. Mandatory.
A single email address or an array of email addresses to whom the email should be sent. Mandatory.
Public Class Methods
Delivers a simple text email message using four options:
-
to
-
from
-
subject
-
body
Examples:
# Send an email to a single user EZ::Email.deliver( :to => 'some_user@hotmail.com', :from => 'me@hotmail.com', :subject => 'Hi', :body => 'How are you?' ) # Send an email to a multiple users EZ::Email.deliver( :to => ['jon@hotmail.com', 'mary@hotmail.com'], :from => 'me@hotmail.com', :subject => 'Hi', :body => 'How are you?' )
This is a shortcut for EZ::Email.new
+ EZ::Email#deliver
.
# File lib/ez/email.rb, line 109 def self.deliver(options) new(options).deliver end
The name of the mail host to use when sending email. The default is whatever the address of your system's 'mailhost' resolves to. If that cannot be determined, your localhost is used.
# File lib/ez/email.rb, line 23 def mail_host @mail_host ||= Resolv.getaddress('mailhost') rescue Resolv::ResolvError @mail_host ||= 'localhost' end
The port to use when sending email. The default is 25.
# File lib/ez/email.rb, line 31 def mail_port @mail_port ||= 25 end
Creates a new EZ::Email
object. As a general rule you won't use this method, but should use EZ::Email.deliver
instead.
# File lib/ez/email.rb, line 54 def initialize(options={}) raise TypeError unless options.is_a?(Hash) options[:from] ||= Etc.getlogin + '@' + Socket.gethostname validate_options(options) @options = options end
Public Instance Methods
Sends the email based on the options passed to the constructor. As a general rule you won't use this method directly, but should use EZ::Email.deliver
instead.
# File lib/ez/email.rb, line 65 def deliver host = EZ::Email.mail_host port = EZ::Email.mail_port to_list = self.to.is_a?(Array) ? self.to : [self.to] Net::SMTP.start(host, port, host){ |smtp| smtp.open_message_stream(self.from, self.to){ |stream| stream.puts "From: #{self.from}" stream.puts "To: " + to_list.join(', ') stream.puts "Subject: #{self.subject}" stream.puts stream.puts self.body } } end
Private Instance Methods
Private method that both validates the hash options, and sets the attribute values.
# File lib/ez/email.rb, line 118 def validate_options(hash) valid = %w[to from subject body] hash.each{ |key, value| key = key.to_s.downcase raise ArgumentError unless valid.include?(key) send("#{key}=", value) } if to.nil? || subject.nil? || body.nil? raise ArgumentError, "Missing :to, :subject or :body" end end