public
Description: Deliver email to local db and have it send by sequel_sendmail later. Attempt at a clone of ar_mailer for merb + sequel.
Clone URL: git://github.com/bricooke/sequel_mailer.git
Search Repo:
the sequel_sendmail binary now exists and is installed. The only thing 
that I know works is the --mailq
bricooke (author)
Sat Mar 15 18:49:22 -0700 2008
commit  3353510f91c5e30129bb0861ec420505a0fcb61b
tree    3ab019ef1a7a051d52fe030eaf7f1f30d56a04d8
parent  8fbb3a264b9cea6980f978a021ce9e1f1dadc2cd
...
1
 
2
3
4
...
18
19
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
...
 
1
2
3
4
...
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
0
@@ -1,4 +1,4 @@
0
-Copyright (c) 2008 YOUR NAME
0
+Copyright (c) 2008 Brian Cooke
0
 
0
 Permission is hereby granted, free of charge, to any person obtaining
0
 a copy of this software and associated documentation files (the
0
@@ -18,4 +18,37 @@
0
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
0
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
0
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
+
0
+
0
+--------------------------------------------------------------------------
0
+ar_mailer LICENSE.txt
0
+--------------------------------------------------------------------------
0
+Original code copyright 2006, 2007, Eric Hodel, The Robot Co-op. All
0
+rights reserved. Some code under other license, see individual files
0
+for details.
0
+
0
+Redistribution and use in source and binary forms, with or without
0
+modification, are permitted provided that the following conditions
0
+are met:
0
+
0
+1. Redistributions of source code must retain the above copyright
0
+ notice, this list of conditions and the following disclaimer.
0
+2. Redistributions in binary form must reproduce the above copyright
0
+ notice, this list of conditions and the following disclaimer in the
0
+ documentation and/or other materials provided with the distribution.
0
+3. Neither the names of the authors nor the names of their contributors
0
+ may be used to endorse or promote products derived from this software
0
+ without specific prior written permission.
0
+
0
+THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
0
+OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
0
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
0
+ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
0
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
0
+OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
0
+OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
0
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
0
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
0
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
0
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
...
3
4
5
6
 
7
8
9
10
...
21
22
23
 
 
24
25
26
 
 
 
27
28
29
...
3
4
5
 
6
7
8
9
10
...
21
22
23
24
25
26
27
 
28
29
30
31
32
33
0
@@ -3,7 +3,7 @@
0
 
0
 PLUGIN = "sequel_mailer"
0
 NAME = "sequel_mailer"
0
-VERSION = "0.0.1"
0
+VERSION = "0.0.2"
0
 AUTHOR = "Brian Cooke"
0
 EMAIL = "bcooke@roobasoft.com"
0
 HOMEPAGE = "http://"
0
0
@@ -21,9 +21,13 @@
0
   s.email = EMAIL
0
   s.homepage = HOMEPAGE
0
   s.add_dependency('merb-more', '>= 0.9.1')
0
+ s.add_dependency('sequel_model', '>= 0.5.0.2')
0
+ s.add_dependency('merb_sequel', '>= 0.9.1')
0
   s.require_path = 'lib'
0
   s.autorequire = PLUGIN
0
- s.files = %w(LICENSE README Rakefile TODO) + Dir.glob("{lib,specs}/**/*")
0
+ s.bindir = "bin"
0
+ s.executables = %w( sequel_sendmail )
0
+ s.files = %w(LICENSE README Rakefile TODO) + Dir.glob("{lib,bin,specs}/**/*")
0
 end
0
 
0
 Rake::GemPackageTask.new(spec) do |pkg|
...
 
 
 
 
...
1
2
3
4
0
@@ -1 +1,5 @@
0
+#!/usr/bin/env ruby
0
+
0
+require 'sequel_mailer/sequel_sendmail'
0
+Sequel::Sendmail.run
...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
0
@@ -1 +1,516 @@
0
+require 'optparse'
0
+require 'net/smtp'
0
+require 'smtp_tls'
0
+require 'rubygems'
0
+require 'sequel'
0
+require 'sequel_model'
0
+require 'merb-core'
0
+require 'merb-more'
0
+
0
+class Object # :nodoc:
0
+ unless respond_to? :path2class then
0
+ def self.path2class(path)
0
+ path.split(/::/).inject self do |k,n| k.const_get n end
0
+ end
0
+ end
0
+end
0
+
0
+##
0
+# Hack in RSET
0
+
0
+module Net # :nodoc:
0
+class SMTP # :nodoc:
0
+
0
+ unless instance_methods.include? 'reset' then
0
+ ##
0
+ # Resets the SMTP connection.
0
+
0
+ def reset
0
+ getok 'RSET'
0
+ end
0
+ end
0
+
0
+end
0
+end
0
+
0
+##
0
+# Sequel::Sendmail delivers email from the email table to the
0
+# SMTP server configured in your application's config/init.rb.
0
+# sequel_sendmail does not work with sendmail delivery.
0
+#
0
+# sequel_mailer can deliver to SMTP with TLS using smtp_tls.rb borrowed from Kyle
0
+# Maxwell's action_mailer_optional_tls plugin. Simply set the :tls option in
0
+# Merb::Mailer.config to true to enable TLS.
0
+#
0
+# See sequel_sendmail -h for the full list of supported options.
0
+#
0
+# The interesting options are:
0
+# * --daemon
0
+# * --mailq
0
+# * --create-migration
0
+# * --create-model
0
+# * --table-name
0
+
0
+class Sequel::Sendmail
0
+
0
+ ##
0
+ # The version of Sequel::Sendmail you are running.
0
+
0
+ VERSION = '0.0.2'
0
+
0
+ ##
0
+ # Maximum number of times authentication will be consecutively retried
0
+
0
+ MAX_AUTH_FAILURES = 2
0
+
0
+ ##
0
+ # Email delivery attempts per run
0
+
0
+ attr_accessor :batch_size
0
+
0
+ ##
0
+ # Seconds to delay between runs
0
+
0
+ attr_accessor :delay
0
+
0
+ ##
0
+ # Maximum age of emails in seconds before they are removed from the queue.
0
+
0
+ attr_accessor :max_age
0
+
0
+ ##
0
+ # Be verbose
0
+
0
+ attr_accessor :verbose
0
+
0
+ ##
0
+ # Sequel class that holds emails
0
+
0
+ attr_reader :email_class
0
+
0
+ ##
0
+ # True if only one delivery attempt will be made per call to run
0
+
0
+ attr_reader :once
0
+
0
+ ##
0
+ # Times authentication has failed
0
+
0
+ attr_accessor :failed_auth_count
0
+
0
+ ##
0
+ # Creates a new migration using +table_name+ and prints it on stdout.
0
+
0
+ def self.create_migration(table_name)
0
+ puts <<-EOF
0
+class #{table_name.classify}Migration < Sequel::Migration
0
+ def up
0
+ create_table "#{table_name.tableize}" do
0
+ primary_key :id
0
+ varchar :from_address
0
+ varchar :to_address
0
+ integer :last_send_attempt, :default => 0
0
+ text :mail
0
+ datetime :created_on
0
+ end
0
+ end
0
+
0
+ def down
0
+ execute "DROP TABLE #{table_name.tableize}"
0
+ end
0
+
0
+end
0
+ EOF
0
+ end
0
+
0
+ ##
0
+ # Creates a new model using +table_name+ and prints it on stdout.
0
+
0
+ def self.create_model(table_name)
0
+ puts <<-EOF
0
+class #{table_name.classify} < Sequel::Model
0
+end
0
+ EOF
0
+ end
0
+
0
+ ##
0
+ # Prints a list of unsent emails and the last delivery attempt, if any.
0
+ #
0
+ def self.mailq(table_name)
0
+ klass = table_name.split('::').inject(Object) { |k,n| k.const_get n }
0
+ emails = klass.all
0
+
0
+ if emails.empty? then
0
+ puts "Mail queue is empty"
0
+ return
0
+ end
0
+
0
+ total_size = 0
0
+
0
+ puts "-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------"
0
+ emails.each do |email|
0
+ size = email.mail.length
0
+ total_size += size
0
+
0
+ create_timestamp = email.created_on rescue
0
+ email.created_at rescue
0
+ Time.at(email.created_date) rescue # for Robot Co-op
0
+ nil
0
+
0
+ created = if create_timestamp.nil? then
0
+ ' Unknown'
0
+ else
0
+ create_timestamp.strftime '%a %b %d %H:%M:%S'
0
+ end
0
+
0
+ puts "%10d %8d %s %s" % [email.id, size, created, email.from_address]
0
+ if email.last_send_attempt > 0 then
0
+ puts "Last send attempt: #{Time.at email.last_send_attempt}"
0
+ end
0
+ puts " #{email.to_address}"
0
+ puts
0
+ end
0
+
0
+ puts "-- #{total_size/1024} Kbytes in #{emails.length} Requests."
0
+ end
0
+
0
+ ##
0
+ # Processes command line options in +args+
0
+
0
+ def self.process_args(args)
0
+ name = File.basename $0
0
+
0
+ options = {}
0
+ options[:Chdir] = '.'
0
+ options[:Daemon] = false
0
+ options[:Delay] = 60
0
+ options[:MaxAge] = 86400 * 7
0
+ options[:Once] = false
0
+ options[:MerbEnv] = ENV['MERB_ENV'] || "development"
0
+ options[:TableName] = 'Email'
0
+
0
+ opts = OptionParser.new do |opts|
0
+ opts.banner = "Usage: #{name} [options]"
0
+ opts.separator ''
0
+
0
+ opts.separator "#{name} scans the email table for new messages and sends them to the"
0
+ opts.separator "website's configured SMTP host."
0
+ opts.separator ''
0
+ opts.separator "#{name} must be run from a Merb application's root."
0
+
0
+ opts.separator ''
0
+ opts.separator 'Sendmail options:'
0
+
0
+ opts.on("-b", "--batch-size BATCH_SIZE",
0
+ "Maximum number of emails to send per delay",
0
+ "Default: Deliver all available emails", Integer) do |batch_size|
0
+ options[:BatchSize] = batch_size
0
+ end
0
+
0
+ opts.on( "--delay DELAY",
0
+ "Delay between checks for new mail",
0
+ "in the database",
0
+ "Default: #{options[:Delay]}", Integer) do |delay|
0
+ options[:Delay] = delay
0
+ end
0
+
0
+ opts.on( "--max-age MAX_AGE",
0
+ "Maxmimum age for an email. After this",
0
+ "it will be removed from the queue.",
0
+ "Set to 0 to disable queue cleanup.",
0
+ "Default: #{options[:MaxAge]} seconds", Integer) do |max_age|
0
+ options[:MaxAge] = max_age
0
+ end
0
+
0
+ opts.on("-o", "--once",
0
+ "Only check for new mail and deliver once",
0
+ "Default: #{options[:Once]}") do |once|
0
+ options[:Once] = once
0
+ end
0
+
0
+ opts.on("-d", "--daemonize",
0
+ "Run as a daemon process",
0
+ "Default: #{options[:Daemon]}") do |daemon|
0
+ options[:Daemon] = true
0
+ end
0
+
0
+ opts.on( "--mailq",
0
+ "Display a list of emails waiting to be sent") do |mailq|
0
+ options[:MailQ] = true
0
+ end
0
+
0
+ opts.separator ''
0
+ opts.separator 'Setup Options:'
0
+
0
+ opts.on( "--create-migration",
0
+ "Prints a migration to add an Email table",
0
+ "to stdout") do |create|
0
+ options[:Migrate] = true
0
+ end
0
+
0
+ opts.on( "--create-model",
0
+ "Prints a model for an Email Sequel",
0
+ "object to stdout") do |create|
0
+ options[:Model] = true
0
+ end
0
+
0
+ opts.separator ''
0
+ opts.separator 'Generic Options:'
0
+
0
+ opts.on("-c", "--chdir PATH",
0
+ "Use PATH for the application path",
0
+ "Default: #{options[:Chdir]}") do |path|
0
+ usage opts, "#{path} is not a directory" unless File.directory? path
0
+ usage opts, "#{path} is not readable" unless File.readable? path
0
+ options[:Chdir] = path
0
+ end
0
+
0
+ opts.on("-e", "--environment MERB_ENV",
0
+ "Set the MERB_ENV constant",
0
+ "Default: #{options[:MerbEnv]}") do |env|
0
+ options[:MerbEnv] = env
0
+ end
0
+
0
+ opts.on("-t", "--table-name TABLE_NAME",
0
+ "Name of table holding emails",
0
+ "Used for both sendmail and",
0
+ "migration creation",
0
+ "Default: #{options[:TableName]}") do |name|
0
+ options[:TableName] = name
0
+ end
0
+
0
+ opts.on("-v", "--[no-]verbose",
0
+ "Be verbose",
0
+ "Default: #{options[:Verbose]}") do |verbose|
0
+ options[:Verbose] = verbose
0
+ end
0
+
0
+ opts.on("-h", "--help",
0
+ "You're looking at it") do
0
+ usage opts
0
+ end
0
+
0
+ opts.separator ''
0
+ end
0
+
0
+ opts.parse! args
0
+
0
+ return options if options.include? :Migrate or options.include? :Model
0
+
0
+ ENV['MERB_ENV'] = options[:MerbEnv]
0
+
0
+ Dir.chdir options[:Chdir] do
0
+ begin
0
+ require 'config/init.rb'
0
+ rescue LoadError
0
+ usage opts, <<-EOF
0
+#{name} must be run from a Merb application's root to deliver email.
0
+#{Dir.pwd} does not appear to be a Merb application root.
0
+ EOF
0
+ end
0
+ end
0
+
0
+ return options
0
+ end
0
+
0
+ ##
0
+ # Processes +args+ and runs as appropriate
0
+
0
+ def self.run(args = ARGV)
0
+ options = process_args args
0
+
0
+ require "app" / "models" / "#{options[:TableName].underscore}.rb"
0
+
0
+ puts "DOING THIS THANG"
0
+ Merb.environment = options[:MerbEnv]
0
+ Merb::Config.setup
0
+ Merb.root = Merb::Config[:merb_root]
0
+ puts "IN ENV = #{Merb.environment}"
0
+ Merb::BootLoader.run
0
+
0
+ if options.include? :Migrate then
0
+ create_migration options[:TableName]
0
+ exit
0
+ elsif options.include? :Model then
0
+ create_model options[:TableName]
0
+ exit
0
+ elsif options.include? :MailQ then
0
+ mailq options[:TableName]
0
+ exit
0
+ end
0
+
0
+ if options[:Daemon] then
0
+ require 'webrick/server'
0
+ WEBrick::Daemon.start
0
+ end
0
+
0
+ new(options).run
0
+
0
+ rescue SystemExit
0
+ raise
0
+ rescue SignalException
0
+ exit
0
+ rescue Exception => e
0
+ $stderr.puts "Unhandled exception #{e.message}(#{e.class}):"
0
+ $stderr.puts "\t#{e.backtrace.join "\n\t"}"
0
+ exit 1
0
+ end
0
+
0
+ ##
0
+ # Prints a usage message to $stderr using +opts+ and exits
0
+
0
+ def self.usage(opts, message = nil)
0
+ if message then
0
+ $stderr.puts message
0
+ $stderr.puts
0
+ end
0
+
0
+ $stderr.puts opts
0
+ exit 1
0
+ end
0
+
0
+ ##
0
+ # Creates a new Sequel::Sendmail.
0
+ #
0
+ # Valid options are:
0
+ # <tt>:BatchSize</tt>:: Maximum number of emails to send per delay
0
+ # <tt>:Delay</tt>:: Delay between deliver attempts
0
+ # <tt>:TableName</tt>:: Table name that stores the emails
0
+ # <tt>:Once</tt>:: Only attempt to deliver emails once when run is called
0
+ # <tt>:Verbose</tt>:: Be verbose.
0
+
0
+ def initialize(options = {})
0
+ options[:Delay] ||= 60
0
+ options[:TableName] ||= 'Email'
0
+ options[:MaxAge] ||= 86400 * 7
0
+
0
+ @batch_size = options[:BatchSize]
0
+ @delay = options[:Delay]
0
+ @email_class = Object.path2class options[:TableName]
0
+ @once = options[:Once]
0
+ @verbose = options[:Verbose]
0
+ @max_age = options[:MaxAge]
0
+
0
+ @failed_auth_count = 0
0
+ end
0
+
0
+ ##
0
+ # Removes emails that have lived in the queue for too long. If max_age is
0
+ # set to 0, no emails will be removed.
0
+
0
+ def cleanup
0
+ return if @max_age == 0
0
+ timeout = Time.now - @max_age
0
+ conditions = ['last_send_attempt > 0 and created_on < ?', timeout]
0
+ mail = @email_class.destroy_all conditions
0
+
0
+ log "expired #{mail.length} emails from the queue"
0
+ end
0
+
0
+ ##
0
+ # Delivers +emails+ to Merb::Mailer's SMTP server and destroys them.
0
+
0
+ def deliver(emails)
0
+ user = Merb::Mailer.config[:user] || Merb::Mailer.config[:user_name]
0
+ Net::SMTP.start Merb::Mailer.config[:host],
0
+ Merb::Mailer.config[:port],
0
+ Merb::Mailer.config[:domain],
0
+ user,
0
+ Merb::Mailer.config[:password],
0
+ Merb::Mailer.config[:auth],
0
+ Merb::Mailer.config[:tls] do |smtp|
0
+ @failed_auth_count = 0
0
+ until emails.empty? do
0
+ email = emails.shift
0
+ begin
0
+ res = smtp.send_message email.mail, email.from_address, email.to_address
0
+ email.destroy
0
+ log "sent email %011d from %s to %s: %p" %
0
+ [email.id, email.from_address, email.to_address, res]
0
+ rescue Net::SMTPFatalError => e
0
+ log "5xx error sending email %d, removing from queue: %p(%s):\n\t%s" %
0
+ [email.id, e.message, e.class, e.backtrace.join("\n\t")]
0
+ email.destroy
0
+ smtp.reset
0
+ rescue Net::SMTPServerBusy => e
0
+ log "server too busy, sleeping #{@delay} seconds"
0
+ sleep delay
0
+ return
0
+ rescue Net::SMTPUnknownError, Net::SMTPSyntaxError, TimeoutError => e
0
+ email.last_send_attempt = Time.now.to_i
0
+ email.save rescue nil
0
+ log "error sending email %d: %p(%s):\n\t%s" %
0
+ [email.id, e.message, e.class, e.backtrace.join("\n\t")]
0
+ smtp.reset
0
+ end
0
+ end
0
+ end
0
+ rescue Net::SMTPAuthenticationError => e
0
+ @failed_auth_count += 1
0
+ if @failed_auth_count >= MAX_AUTH_FAILURES then
0
+ log "authentication error, giving up: #{e.message}"
0
+ raise e
0
+ else
0
+ log "authentication error, retrying: #{e.message}"
0
+ end
0
+ sleep delay
0
+ rescue Net::SMTPServerBusy, SystemCallError, OpenSSL::SSL::SSLError
0
+ # ignore SMTPServerBusy/EPIPE/ECONNRESET from Net::SMTP.start's ensure
0
+ end
0
+
0
+ ##
0
+ # Prepares ar_sendmail for exiting
0
+
0
+ def do_exit
0
+ log "caught signal, shutting down"
0
+ exit
0
+ end
0
+
0
+ ##
0
+ # Returns emails in email_class that haven't had a delivery attempt in the
0
+ # last 300 seconds.
0
+
0
+ def find_emails
0
+ options = { :conditions => ['last_send_attempt < ?', Time.now.to_i - 300] }
0
+ options[:limit] = batch_size unless batch_size.nil?
0
+ mail = @email_class.find :all, options
0
+
0
+ log "found #{mail.length} emails to send"
0
+ mail
0
+ end
0
+
0
+ ##
0
+ # Installs signal handlers to gracefully exit.
0
+
0
+ def install_signal_handlers
0
+ trap 'TERM' do do_exit end
0
+ trap 'INT' do do_exit end
0
+ end
0
+
0
+ ##
0
+ # Logs +message+ if verbose
0
+
0
+ def log(message)
0
+ $stderr.puts message if @verbose
0
+ ActionMailer::Base.logger.info "ar_sendmail: #{message}"
0
+ end
0
+
0
+ ##
0
+ # Scans for emails and delivers them every delay seconds. Only returns if
0
+ # once is true.
0
+
0
+ def run
0
+ install_signal_handlers
0
+
0
+ loop do
0
+ now = Time.now
0
+ begin
0
+ cleanup
0
+ deliver find_emails
0
+ end
0
+ break if @once
0
+ sleep @delay if now + @delay > Time.now
0
+ end
0
+ end
0
+end
...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
0
@@ -1 +1,106 @@
0
+# Original code believed public domain from ruby-talk or ruby-core email.
0
+# Modifications by Kyle Maxwell <kyle@kylemaxwell.com> used under MIT license.
0
+
0
+require "openssl"
0
+require "net/smtp"
0
+
0
+# :stopdoc:
0
+
0
+class Net::SMTP
0
+
0
+ class << self
0
+ send :remove_method, :start
0
+ end
0
+
0
+ def self.start( address, port = nil,
0
+ helo = 'localhost.localdomain',
0
+ user = nil, secret = nil, authtype = nil, use_tls = false,
0
+ &block) # :yield: smtp
0
+ new(address, port).start(helo, user, secret, authtype, use_tls, &block)
0
+ end
0
+
0
+ alias tls_old_start start
0
+
0
+ def start( helo = 'localhost.localdomain',
0
+ user = nil, secret = nil, authtype = nil, use_tls = false ) # :yield: smtp
0
+ start_method = use_tls ? :do_tls_start : :do_start
0
+ if block_given?
0
+ begin
0
+ send start_method, helo, user, secret, authtype
0
+ return yield(self)
0
+ ensure
0
+ do_finish
0
+ end
0
+ else
0
+ send start_method, helo, user, secret, authtype
0
+ return self
0
+ end
0
+ end
0
+
0
+ private
0
+
0
+ def do_tls_start(helodomain, user, secret, authtype)
0
+ raise IOError, 'SMTP session already started' if @started
0
+ check_auth_args user, secret, authtype if user or secret
0
+
0
+ sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
0
+ @socket = Net::InternetMessageIO.new(sock)
0
+ @socket.read_timeout = 60 #@read_timeout
0
+ @socket.debug_output = STDERR #@debug_output
0
+
0
+ check_response(critical { recv_response() })
0
+ do_helo(helodomain)
0
+
0
+ raise 'openssl library not installed' unless defined?(OpenSSL)
0
+ starttls
0
+ ssl = OpenSSL::SSL::SSLSocket.new(sock)
0
+ ssl.sync_close = true
0
+ ssl.connect
0
+ @socket = Net::InternetMessageIO.new(ssl)
0
+ @socket.read_timeout = 60 #@read_timeout
0
+ @socket.debug_output = STDERR #@debug_output
0
+ do_helo(helodomain)
0
+
0
+ authenticate user, secret, authtype if user
0
+ @started = true
0
+ ensure
0
+ unless @started
0
+ # authentication failed, cancel connection.
0
+ @socket.close if not @started and @socket and not @socket.closed?
0
+ @socket = nil
0
+ end
0
+ end
0
+
0
+ def do_helo(helodomain)
0
+ begin
0
+ if @esmtp
0
+ ehlo helodomain
0
+ else
0
+ helo helodomain
0
+ end
0
+ rescue Net::ProtocolError
0
+ if @esmtp
0
+ @esmtp = false
0
+ @error_occured = false
0
+ retry
0
+ end
0
+ raise
0
+ end
0
+ end
0
+
0
+ def starttls
0
+ getok('STARTTLS')
0
+ end
0
+
0
+ alias tls_old_quit quit
0
+
0
+ def quit
0
+ begin
0
+ getok('QUIT')
0
+ rescue EOFError
0
+ end
0
+ end
0
+
0
+end unless Net::SMTP.private_method_defined? :do_tls_start or
0
+ Net::SMTP.method_defined? :tls?

Comments

    No one has commented yet.