Class: EventMachine::Protocols::SmtpClient

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

Constant Summary

Constants included from LineText2

LineText2::MaxBinaryLength, LineText2::MaxLineLength

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_timeout, #errback, #fail, future, #set_deferred_failure, #set_deferred_status, #set_deferred_success, #succeed, #timeout

Methods inherited from Connection

#associate_callback_target, #close_connection, #close_connection_after_writing, #comm_inactivity_timeout, #comm_inactivity_timeout=, #detach, #error?, #get_outbound_data_size, #get_peer_cert, #get_peername, #get_pid, #get_sockname, #get_status, #initialize, new, #receive_data, #reconnect, #send_data, #send_datagram, #send_file_data, #set_comm_inactivity_timeout, #ssl_handshake_completed, #start_tls, #stream_file_data

Constructor Details

This class inherits a constructor from EventMachine::Connection

Instance Attribute Details

#args=(value) ⇒ Object (writeonly)

Sets the attribute args

Parameters:

  • value

    the value to set the attribute args to.



111
112
113
# File 'lib/protocols/smtpclient.rb', line 111

def args=(value)
  @args = value
end

Class Method Details

.send(args = {}) ⇒ Object

This is the external entry point.

The argument is a hash containing these values: :host => 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. 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.

:header => Required 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, 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. I think the :body parameter should remain as it is, and we
should add a :content parameter that contains autoconversions and/or conversion parameters.
Then we can check if either :body or :content is present and do the right thing.

:verbose => Optional. If true, will cause a lot of information (including the server-side of the

conversation) to be dumped to $>.


79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/protocols/smtpclient.rb', line 79

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



118
119
120
121
# File 'lib/protocols/smtpclient.rb', line 118

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

#invoke_authObject

Perform an authentication. If the caller didn’t request one, then fall through to the mail-from state.



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/protocols/smtpclient.rb', line 208

def invoke_auth
	if @args[:auth]
		if @args[:auth][:type] == :plain
			psw = @args[:auth][:password]
			if psw.respond_to?(:call)
				psw = psw.call
			end
			#str = Base64::encode64("\0#{@args[:auth][:username]}\0#{psw}").chomp
			str = ["\0#{@args[:auth][:username]}\0#{psw}"].pack("m").chomp
			send_data "AUTH PLAIN #{str}\r\n"
			@responder = :receive_auth_response
		else
			return invoke_internal_error("unsupported auth type")
		end
	else
		invoke_mail_from
	end
end

#invoke_dataObject



261
262
263
264
# File 'lib/protocols/smtpclient.rb', line 261

def invoke_data
	send_data "DATA\r\n"
	@responder = :receive_data_response
end

#invoke_errorObject

We encountered an error from the server and will close the connection. Use the error and message the server returned.



153
154
155
156
157
158
159
160
161
# File 'lib/protocols/smtpclient.rb', line 153

def invoke_error
	@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
	send_data "QUIT\r\n"
	close_connection_after_writing
end

#invoke_internal_error(msg = "???") ⇒ Object

We encountered an error on our side of the protocol and will close the connection. Use an extra-protocol error code (900) and use the message from the caller.



166
167
168
169
170
171
172
173
174
# File 'lib/protocols/smtpclient.rb', line 166

def invoke_internal_error msg = "???"
	@return_values.elapsed_time = Time.now - @return_values.start_time
	@return_values.responder = @responder
	@return_values.code = 900
	@return_values.message = msg
	set_deferred_status :failed, @return_values
	send_data "QUIT\r\n"
	close_connection_after_writing
end

#invoke_mail_fromObject



231
232
233
234
# File 'lib/protocols/smtpclient.rb', line 231

def invoke_mail_from
	send_data "MAIL FROM: <#{@args[:from]}>\r\n"
	@responder = :receive_mail_from_response
end

#invoke_rcpt_toObject



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/protocols/smtpclient.rb', line 240

def invoke_rcpt_to
	@rcpt_responses ||= []
	l = @rcpt_responses.length
	to = @args[:to].is_a?(Array) ? @args[:to] : [@args[:to].to_s]
	if l < to.length
		send_data "RCPT TO: <#{to[l]}>\r\n"
		@responder = :receive_rcpt_to_response
	else
		e = @rcpt_responses.select {|rr| rr.last == 2}
		if e and e.length > 0
			invoke_data
		else
			invoke_error
		end
	end
end

#invoke_starttlsObject



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

def invoke_starttls
	if @args[:starttls]
		# It would be more sociable to first ask if @server_caps contains
		# the string "STARTTLS" before we invoke it, but hey, life's too short.
		send_data "STARTTLS\r\n"
		@responder = :receive_starttls_response
	else
		invoke_auth
	end
end

#post_initObject



113
114
115
116
# File 'lib/protocols/smtpclient.rb', line 113

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

#receive_auth_responseObject



226
227
228
229
# File 'lib/protocols/smtpclient.rb', line 226

def receive_auth_response
	return invoke_error unless @range == 2
	invoke_mail_from
end

#receive_data_responseObject



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/protocols/smtpclient.rb', line 265

def receive_data_response
	return invoke_error unless @range == 3

	# The data to send can be given either in @args[:content] (an array or string of raw data
	# which MUST be in correct SMTP body format, including a trailing dot line), or a header and
	# body given in @args[:header] and @args[:body].
	#
	if @args[:content]
		send_data @args[:content].to_s
	else
		# The header can be a hash or an array.
		if @args[:header].is_a?(Hash)
			(@args[:header] || {}).each {|k,v| send_data "#{k}: #{v}\r\n" }
		else
			send_data @args[:header].to_s
		end
		send_data "\r\n"

		if @args[:body].is_a?(Array)
			@args[:body].each {|e| send_data e}
		else
			send_data @args[:body].to_s
		end

		send_data "\r\n.\r\n"
	end

	@responder = :receive_message_response
end

#receive_ehlo_responseObject



182
183
184
185
186
# File 'lib/protocols/smtpclient.rb', line 182

def receive_ehlo_response
	return invoke_error unless @range == 2
	@server_caps = @msg
	invoke_starttls
end

#receive_line(ln) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
# File 'lib/protocols/smtpclient.rb', line 138

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

#receive_mail_from_responseObject



235
236
237
238
# File 'lib/protocols/smtpclient.rb', line 235

def receive_mail_from_response
	return invoke_error unless @range == 2
	invoke_rcpt_to
end

#receive_message_responseObject



294
295
296
297
298
299
300
301
302
303
304
# File 'lib/protocols/smtpclient.rb', line 294

def receive_message_response
	return invoke_error unless @range == 2
	send_data "QUIT\r\n"
	close_connection_after_writing
	@succeeded = true
	@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 :succeeded, @return_values
end

#receive_rcpt_to_responseObject



256
257
258
259
# File 'lib/protocols/smtpclient.rb', line 256

def receive_rcpt_to_response
	@rcpt_responses << [@code, @msg, @range]
	invoke_rcpt_to
end

#receive_signonObject



176
177
178
179
180
# File 'lib/protocols/smtpclient.rb', line 176

def receive_signon
	return invoke_error unless @range == 2
	send_data "EHLO #{@args[:domain]}\r\n"
	@responder = :receive_ehlo_response
end

#receive_starttls_responseObject



198
199
200
201
202
# File 'lib/protocols/smtpclient.rb', line 198

def receive_starttls_response
	return invoke_error unless @range == 2
	start_tls
	invoke_auth
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).



128
129
130
131
132
133
134
135
136
# File 'lib/protocols/smtpclient.rb', line 128

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