Class: EventMachine::Protocols::SmtpClient

Inherits:
Connection
  • Object
show all
Includes:
Deferrable, LineText2
Defined in:
lib/em/protocols/smtpclient.rb

Overview

Simple SMTP client

Sending generated emails (using Mail)

mail = Mail.new do
  from    '[email protected]'
  to      '[email protected]'
  subject 'This is a test email'
  body    'Hello, world!'
end

email = EM::P::SmtpClient.send(
  :domain=>'example.com',
  :from=>mail.from.first,
  :to=>mail.to,
  :message=>mail.to_s
)

Examples:

email = EM::Protocols::SmtpClient.send(
  :domain=>"example.com",
  :host=>'localhost',
  :port=>25, # optional, defaults 25
  :starttls=>true, # use ssl
  :from=>"[email protected]",
  :to=> ["[email protected]", "[email protected]"],
  :header=> {"Subject" => "This is a subject line"},
  :body=> "This is the body of the email"
)
email.callback{
  puts 'Email sent!'
}
email.errback{ |e|
  puts 'Email failed!'
}

Constant Summary

Constants included from LineText2

LineText2::MaxBinaryLength

Constants included from Deferrable

Deferrable::Pool

Instance Attribute Summary collapse

Attributes inherited from Connection

#signature

Class Method Summary collapse

Instance Method Summary collapse

Methods included from LineText2

#receive_binary_data, #receive_data, #receive_end_of_binary_data, #set_binary_mode, #set_delimiter, #set_line_mode, #set_text_mode

Methods included from Deferrable

#callback, #cancel_callback, #cancel_errback, #cancel_timeout, #errback, #fail, future, #set_deferred_status, #succeed, #timeout

Methods inherited from Connection

#associate_callback_target, #close_connection, #close_connection_after_writing, #comm_inactivity_timeout, #comm_inactivity_timeout=, #detach, #error?, #get_cipher_bits, #get_cipher_name, #get_cipher_protocol, #get_idle_time, #get_outbound_data_size, #get_peer_cert, #get_peername, #get_pid, #get_proxied_bytes, #get_sni_hostname, #get_sock_opt, #get_sockname, #get_status, new, #notify_readable=, #notify_readable?, #notify_writable=, #notify_writable?, #pause, #paused?, #pending_connect_timeout, #pending_connect_timeout=, #proxy_completed, #proxy_incoming_to, #proxy_target_unbound, #receive_data, #reconnect, #resume, #send_data, #send_datagram, #send_file_data, #set_sock_opt, #ssl_handshake_completed, #ssl_verify_peer, #start_tls, #stop_proxying, #stream_file_data

Constructor Details

#initializeSmtpClient

Returns a new instance of SmtpClient.



71
72
73
74
75
76
# File 'lib/em/protocols/smtpclient.rb', line 71

def initialize
  @succeeded = nil
  @responder = nil
  @code = nil
  @msg = nil
end

Instance Attribute Details

#args=(value) ⇒ Object (writeonly)

Sets the attribute args

Parameters:

  • value

    the value to set the attribute args to.



169
170
171
# File 'lib/em/protocols/smtpclient.rb', line 169

def args=(value)
  @args = value
end

Class Method Details

.send(args = {}) ⇒ Object

:host => required String

a string containing the IP address or host name of the SMTP server to connect to.

:port => optional

defaults to 25.

:domain => required String

This is passed as the argument to the EHLO command.

:starttls => optional Boolean

If it evaluates true, then the client will initiate STARTTLS with
the server, and abort the connection if the negotiation doesn't succeed.
TODO, need to be able to pass certificate parameters with this option.

:auth => optional Hash of auth parameters

If not given, then no auth will be attempted.
(In that case, the connection will be aborted if the server requires auth.)
Specify the hash value :type to determine the auth type, along with additional parameters
depending on the type.
Currently only :type => :plain is supported. Pass additional parameters :username (String),
and :password (either a String or a Proc that will be called at auth-time).

@example
  :auth => {:type=>:plain, :username=>"[email protected]", :password=>"mouse"}

:from => required String

Specifies the sender of the message. Will be passed as the argument
to the MAIL FROM. Do NOT enclose the argument in angle-bracket (<>) characters.
The connection will abort if the server rejects the value.

:to => required String or Array of Strings

The recipient(s) of the message. Do NOT enclose
any of the values in angle-brackets (<>) characters. It's NOT a fatal error if one or more
recipients are rejected by the server. (Of course, if ALL of them are, the server will most
likely trigger an error when we try to send data.) An array of codes containing the status
of each requested recipient is available after the call completes. TODO, we should define
an overridable stub that will be called on rejection of a recipient or a sender, giving
user code the chance to try again or abort the connection.

One of either :message, :content, or :header and :body is required:

:message => String

A valid RFC2822 Internet Message.

:content => String

Raw data which MUST be in correct SMTP body format, with escaped leading dots and a trailing
dot line.

:header => String or Hash of values to be transmitted in the header of the message.

The hash keys are the names of the headers (do NOT append a trailing colon), and the values
are strings containing the header values. TODO, support Arrays of header values, which would
cause us to send that specific header line more than once.

@example
  :header => {"Subject" => "Bogus", "CC" => "[email protected]"}

:body => Optional String or Array of Strings, defaults blank.

This will be passed as the body of the email message.
TODO, this needs to be significantly beefed up. As currently written, this requires the caller
to properly format the input into CRLF-delimited lines of 7-bit characters in the standard
SMTP transmission format. We need to be able to automatically convert binary data, and add
correct line-breaks to text data.

:verbose => Optional.

If true, will cause a lot of information (including the server-side of the
conversation) to be dumped to $>.


138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/em/protocols/smtpclient.rb', line 138

def self.send args={}
  args[:port] ||= 25
  args[:body] ||= ""

=begin
(I don't think it's possible for EM#connect to throw an exception under normal
circumstances, so this original code is stubbed out. A connect-failure will result
in the #unbind method being called without calling #connection_completed.)
begin
  EventMachine.connect( args[:host], args[:port], self) {|c|
    # According to the EM docs, we will get here AFTER post_init is called.
    c.args = args
    c.set_comm_inactivity_timeout 60
  }
rescue
  # We'll get here on a connect error. This code mimics the effect
  # of a call to invoke_internal_error. Would be great to DRY this up.
  # (Actually, it may be that we never get here, if EM#connect catches
  # its errors internally.)
  d = EM::DefaultDeferrable.new
  d.set_deferred_status(:failed, {:error=>[:connect, 500, "unable to connect to server"]})
  d
end
=end
  EventMachine.connect( args[:host], args[:port], self) {|c|
    # According to the EM docs, we will get here AFTER post_init is called.
    c.args = args
    c.set_comm_inactivity_timeout 60
  }
end

Instance Method Details

#connection_completedObject



178
179
180
181
# File 'lib/em/protocols/smtpclient.rb', line 178

def connection_completed
  @responder = :receive_signon
  @msg = []
end

#post_initObject



172
173
174
175
# File 'lib/em/protocols/smtpclient.rb', line 172

def post_init
  @return_values = OpenStruct.new
  @return_values.start_time = Time.now
end

#receive_line(ln) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
# File 'lib/em/protocols/smtpclient.rb', line 200

def receive_line ln
  $>.puts ln if @args[:verbose]
  @range = ln[0...1].to_i
  @code = ln[0...3].to_i
  @msg << ln[4..-1]
  unless ln[3...4] == '-'
    $>.puts @responder if @args[:verbose]
    send @responder
    @msg.clear
  end
end

#unbindObject

We can get here in a variety of ways, all of them being failures unless the @succeeded flag is set. If a protocol success was recorded, then don’t set a deferred success because the caller will already have done it (no need to wait until the connection closes to invoke the callbacks).



189
190
191
192
193
194
195
196
197
# File 'lib/em/protocols/smtpclient.rb', line 189

def unbind
  unless @succeeded
    @return_values.elapsed_time = Time.now - @return_values.start_time
    @return_values.responder = @responder
    @return_values.code = @code
    @return_values.message = @msg
    set_deferred_status(:failed, @return_values)
  end
end