prioritized_ar_mailer 2.1.11

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,2 @@
1
+ class <%= class_name %> < ActiveRecord::Base
2
+ end
@@ -0,0 +1,40 @@
1
+ ##
2
+ # Adds sending email through an ActiveRecord table as a delivery method for
3
+ # ActionMailer.
4
+ #
5
+
6
+ class ActionMailer::Base
7
+
8
+ ##
9
+ # Set the email class for deliveries. Handle class reloading issues which prevents caching the email class.
10
+ #
11
+ @@email_class_name = 'Email'
12
+
13
+ def self.email_class=(klass)
14
+ @@email_class_name = klass.to_s
15
+ end
16
+
17
+ def self.email_class
18
+ @@email_class_name.constantize
19
+ end
20
+
21
+ ##
22
+ # Adds +mail+ to the Email table. Only the first From address for +mail+ is
23
+ # used.
24
+
25
+ def perform_delivery_activerecord(mail)
26
+ require "action_mailer/ar_sendmail"
27
+ destinations = mail.destinations
28
+ mail.ready_to_send
29
+ sender = (mail['return-path'] && mail['return-path'].spec) || mail.from.first
30
+ destinations.each do |destination|
31
+ m = self.class.email_class.create :mail => mail.encoded, :to => destination, :from => sender, :priority => (@priority.present? ? @priority : 3)
32
+ if m.priority==-1
33
+ sendmail = ActionMailer::ARSendmail.new
34
+ sendmail.deliver([m])
35
+ m.destroy
36
+ end
37
+ end
38
+ end
39
+
40
+ end
@@ -0,0 +1,481 @@
1
+ require 'optparse'
2
+ require 'net/smtp'
3
+ require 'smtp_tls' unless Net::SMTP.instance_methods.include?("enable_starttls_auto")
4
+
5
+ ##
6
+ # Hack in RSET
7
+
8
+ module Net # :nodoc:
9
+ class SMTP # :nodoc:
10
+
11
+ unless instance_methods.include? 'reset' then
12
+ ##
13
+ # Resets the SMTP connection.
14
+
15
+ def reset
16
+ getok 'RSET'
17
+ end
18
+ end
19
+
20
+ end
21
+ end
22
+
23
+ ##
24
+ # ActionMailer::ARSendmail delivers email from the email table to the
25
+ # SMTP server configured in your application's config/environment.rb.
26
+ # ar_sendmail does not work with sendmail delivery.
27
+ #
28
+ # ar_mailer can deliver to SMTP with TLS using smtp_tls.rb borrowed from Kyle
29
+ # Maxwell's action_mailer_optional_tls plugin. Simply set the :tls option in
30
+ # ActionMailer::Base's smtp_settings to true to enable TLS.
31
+ #
32
+ # See ar_sendmail -h for the full list of supported options.
33
+ #
34
+ # The interesting options are:
35
+ # * --daemon
36
+ # * --mailq
37
+
38
+ module ActionMailer; end
39
+
40
+ class ActionMailer::ARSendmail
41
+
42
+ ##
43
+ # The version of ActionMailer::ARSendmail you are running.
44
+
45
+ VERSION = '2.1.11'
46
+
47
+ ##
48
+ # Maximum number of times authentication will be consecutively retried
49
+
50
+ MAX_AUTH_FAILURES = 2
51
+
52
+ ##
53
+ # Email delivery attempts per run
54
+
55
+ attr_accessor :batch_size
56
+
57
+ ##
58
+ # Seconds to delay between runs
59
+
60
+ attr_accessor :delay
61
+
62
+ ##
63
+ # Maximum age of emails in seconds before they are removed from the queue.
64
+
65
+ attr_accessor :max_age
66
+
67
+ ##
68
+ # Be verbose
69
+
70
+ attr_accessor :verbose
71
+
72
+
73
+ ##
74
+ # True if only one delivery attempt will be made per call to run
75
+
76
+ attr_reader :once
77
+
78
+ ##
79
+ # Times authentication has failed
80
+
81
+ attr_accessor :failed_auth_count
82
+
83
+ @@pid_file = nil
84
+
85
+ def self.remove_pid_file
86
+ if @@pid_file
87
+ require 'shell'
88
+ sh = Shell.new
89
+ sh.rm @@pid_file
90
+ end
91
+ end
92
+
93
+ ##
94
+ # Prints a list of unsent emails and the last delivery attempt, if any.
95
+ #
96
+ # If ActiveRecord::Timestamp is not being used the arrival time will not be
97
+ # known. See http://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html
98
+ # to learn how to enable ActiveRecord::Timestamp.
99
+
100
+ def self.mailq
101
+ emails = ActionMailer::Base.email_class.find :all, :order=>"priority desc"
102
+ if emails.empty? then
103
+ puts "Mail queue is empty"
104
+ return
105
+ end
106
+
107
+ total_size = 0
108
+
109
+ puts "-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------"
110
+ emails.each do |email|
111
+ size = email.mail.length
112
+ total_size += size
113
+
114
+ create_timestamp = email.created_on rescue
115
+ email.created_at rescue
116
+ Time.at(email.created_date) rescue # for Robot Co-op
117
+ nil
118
+
119
+ created = if create_timestamp.nil? then
120
+ ' Unknown'
121
+ else
122
+ create_timestamp.strftime '%a %b %d %H:%M:%S'
123
+ end
124
+
125
+ puts "%10d %8d %s %s" % [email.id, size, created, email.from]
126
+ if email.last_send_attempt > 0 then
127
+ puts "Last send attempt: #{Time.at email.last_send_attempt}"
128
+ end
129
+ puts " #{email.to}"
130
+ puts
131
+ end
132
+
133
+ puts "-- #{total_size/1024} Kbytes in #{emails.length} Requests."
134
+ end
135
+
136
+ ##
137
+ # Processes command line options in +args+
138
+
139
+ def self.process_args(args)
140
+ name = File.basename $0
141
+
142
+ options = {}
143
+ options[:Chdir] = '.'
144
+ options[:Daemon] = false
145
+ options[:Delay] = 60
146
+ options[:MaxAge] = 86400 * 7
147
+ options[:Once] = false
148
+ options[:RailsEnv] = ENV['RAILS_ENV']
149
+ options[:Pidfile] = options[:Chdir] + '/log/ar_sendmail.pid'
150
+
151
+ opts = OptionParser.new do |opts|
152
+ opts.banner = "Usage: #{name} [options]"
153
+ opts.separator ''
154
+
155
+ opts.separator "#{name} scans the email table for new messages and sends them to the"
156
+ opts.separator "website's configured SMTP host."
157
+ opts.separator ''
158
+ opts.separator "#{name} must be run from a Rails application's root."
159
+
160
+ opts.separator ''
161
+ opts.separator 'Sendmail options:'
162
+
163
+ opts.on("-b", "--batch-size BATCH_SIZE",
164
+ "Maximum number of emails to send per delay",
165
+ "Default: Deliver all available emails", Integer) do |batch_size|
166
+ options[:BatchSize] = batch_size
167
+ end
168
+
169
+ opts.on( "--delay DELAY",
170
+ "Delay between checks for new mail",
171
+ "in the database",
172
+ "Default: #{options[:Delay]}", Integer) do |delay|
173
+ options[:Delay] = delay
174
+ end
175
+
176
+ opts.on( "--max-age MAX_AGE",
177
+ "Maxmimum age for an email. After this",
178
+ "it will be removed from the queue.",
179
+ "Set to 0 to disable queue cleanup.",
180
+ "Default: #{options[:MaxAge]} seconds", Integer) do |max_age|
181
+ options[:MaxAge] = max_age
182
+ end
183
+
184
+ opts.on("-o", "--once",
185
+ "Only check for new mail and deliver once",
186
+ "Default: #{options[:Once]}") do |once|
187
+ options[:Once] = once
188
+ end
189
+
190
+ opts.on("-d", "--daemonize",
191
+ "Run as a daemon process",
192
+ "Default: #{options[:Daemon]}") do |daemon|
193
+ options[:Daemon] = true
194
+ end
195
+
196
+ opts.on("-p", "--pidfile PIDFILE",
197
+ "Set the pidfile location",
198
+ "Default: #{options[:Chdir]}#{options[:Pidfile]}", String) do |pidfile|
199
+ options[:Pidfile] = pidfile
200
+ end
201
+
202
+ opts.on( "--mailq",
203
+ "Display a list of emails waiting to be sent") do |mailq|
204
+ options[:MailQ] = true
205
+ end
206
+
207
+ opts.separator ''
208
+ opts.separator 'Setup Options:'
209
+
210
+ opts.separator ''
211
+ opts.separator 'Generic Options:'
212
+
213
+ opts.on("-c", "--chdir PATH",
214
+ "Use PATH for the application path",
215
+ "Default: #{options[:Chdir]}") do |path|
216
+ usage opts, "#{path} is not a directory" unless File.directory? path
217
+ usage opts, "#{path} is not readable" unless File.readable? path
218
+ options[:Chdir] = path
219
+ end
220
+
221
+ opts.on("-e", "--environment RAILS_ENV",
222
+ "Set the RAILS_ENV constant",
223
+ "Default: #{options[:RailsEnv]}") do |env|
224
+ options[:RailsEnv] = env
225
+ end
226
+
227
+ opts.on("-v", "--[no-]verbose",
228
+ "Be verbose",
229
+ "Default: #{options[:Verbose]}") do |verbose|
230
+ options[:Verbose] = verbose
231
+ end
232
+
233
+ opts.on("-h", "--help",
234
+ "You're looking at it") do
235
+ usage opts
236
+ end
237
+
238
+ opts.on("--version", "Version of ARMailer") do
239
+ usage "ar_mailer #{VERSION} (adzap fork)"
240
+ end
241
+
242
+ opts.separator ''
243
+ end
244
+
245
+ opts.parse! args
246
+
247
+ ENV['RAILS_ENV'] = options[:RailsEnv]
248
+
249
+ Dir.chdir options[:Chdir] do
250
+ begin
251
+ require 'config/environment'
252
+ require 'action_mailer/ar_mailer'
253
+ rescue LoadError
254
+ usage opts, <<-EOF
255
+ #{name} must be run from a Rails application's root to deliver email.
256
+ #{Dir.pwd} does not appear to be a Rails application root.
257
+ EOF
258
+ end
259
+ end
260
+
261
+ return options
262
+ end
263
+
264
+ ##
265
+ # Processes +args+ and runs as appropriate
266
+
267
+ def self.run(args = ARGV)
268
+ options = process_args args
269
+
270
+ if options.include? :MailQ then
271
+ mailq
272
+ exit
273
+ end
274
+
275
+ if options[:Daemon] then
276
+ require 'webrick/server'
277
+ @@pid_file = File.expand_path(options[:Pidfile], options[:Chdir])
278
+ if File.exists? @@pid_file
279
+ # check to see if process is actually running
280
+ pid = ''
281
+ File.open(@@pid_file, 'r') {|f| pid = f.read.chomp }
282
+ if system("ps -p #{pid} | grep #{pid}") # returns true if process is running, o.w. false
283
+ $stderr.puts "Warning: The pid file #{@@pid_file} exists and ar_sendmail is running. Shutting down."
284
+ exit -1
285
+ else
286
+ # not running, so remove existing pid file and continue
287
+ self.remove_pid_file
288
+ $stderr.puts "ar_sendmail is not running. Removing existing pid file and starting up..."
289
+ end
290
+ end
291
+ WEBrick::Daemon.start
292
+ File.open(@@pid_file, 'w') {|f| f.write("#{Process.pid}\n")}
293
+ end
294
+
295
+ new(options).run
296
+
297
+ rescue SystemExit
298
+ raise
299
+ rescue SignalException
300
+ exit
301
+ rescue Exception => e
302
+ $stderr.puts "Unhandled exception #{e.message}(#{e.class}):"
303
+ $stderr.puts "\t#{e.backtrace.join "\n\t"}"
304
+ exit -2
305
+ end
306
+
307
+ ##
308
+ # Prints a usage message to $stderr using +opts+ and exits
309
+
310
+ def self.usage(opts, message = nil)
311
+ if message then
312
+ $stderr.puts message
313
+ $stderr.puts
314
+ end
315
+
316
+ $stderr.puts opts
317
+ exit 1
318
+ end
319
+
320
+ ##
321
+ # Creates a new ARSendmail.
322
+ #
323
+ # Valid options are:
324
+ # <tt>:BatchSize</tt>:: Maximum number of emails to send per delay
325
+ # <tt>:Delay</tt>:: Delay between deliver attempts
326
+ # <tt>:Once</tt>:: Only attempt to deliver emails once when run is called
327
+ # <tt>:Verbose</tt>:: Be verbose.
328
+
329
+ def initialize(options = {})
330
+ options[:Delay] ||= 60
331
+ options[:MaxAge] ||= 86400 * 7
332
+
333
+ @batch_size = options[:BatchSize]
334
+ @delay = options[:Delay]
335
+ @once = options[:Once]
336
+ @verbose = options[:Verbose]
337
+ @max_age = options[:MaxAge]
338
+
339
+ @failed_auth_count = 0
340
+ end
341
+
342
+ ##
343
+ # Removes emails that have lived in the queue for too long. If max_age is
344
+ # set to 0, no emails will be removed.
345
+
346
+ def cleanup
347
+ return if @max_age == 0
348
+ timeout = Time.now - @max_age
349
+ conditions = ['last_send_attempt > 0 and created_on < ?', timeout]
350
+ mail = ActionMailer::Base.email_class.destroy_all conditions
351
+
352
+ log "expired #{mail.length} emails from the queue"
353
+ end
354
+
355
+ ##
356
+ # Delivers +emails+ to ActionMailer's SMTP server and destroys them.
357
+
358
+ def deliver(emails)
359
+ settings = [
360
+ smtp_settings[:domain],
361
+ (smtp_settings[:user] || smtp_settings[:user_name]),
362
+ smtp_settings[:password],
363
+ smtp_settings[:authentication]
364
+ ]
365
+
366
+ smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
367
+ if smtp.respond_to?(:enable_starttls_auto)
368
+ smtp.enable_starttls_auto unless smtp_settings[:tls] == false
369
+ else
370
+ settings << smtp_settings[:tls]
371
+ end
372
+
373
+ smtp.start(*settings) do |session|
374
+ @failed_auth_count = 0
375
+ until emails.empty? do
376
+ email = emails.shift
377
+ begin
378
+ res = session.send_message email.mail, email.from, email.to
379
+ email.destroy
380
+ log "sent email %011d from %s to %s: %p" %
381
+ [email.id, email.from, email.to, res]
382
+ rescue Net::SMTPFatalError => e
383
+ log "5xx error sending email %d, removing from queue: %p(%s):\n\t%s" %
384
+ [email.id, e.message, e.class, e.backtrace.join("\n\t")]
385
+ email.destroy
386
+ session.reset
387
+ rescue Net::SMTPServerBusy => e
388
+ log "server too busy, stopping delivery cycle"
389
+ return
390
+ rescue Net::SMTPUnknownError, Net::SMTPSyntaxError, TimeoutError, Timeout::Error => e
391
+ email.last_send_attempt = Time.now.to_i
392
+ email.save rescue nil
393
+ log "error sending email %d: %p(%s):\n\t%s" %
394
+ [email.id, e.message, e.class, e.backtrace.join("\n\t")]
395
+ session.reset
396
+ end
397
+ end
398
+ end
399
+ rescue Net::SMTPAuthenticationError => e
400
+ @failed_auth_count += 1
401
+ if @failed_auth_count >= MAX_AUTH_FAILURES then
402
+ log "authentication error, giving up: #{e.message}"
403
+ raise e
404
+ else
405
+ log "authentication error, retrying: #{e.message}"
406
+ end
407
+ sleep delay
408
+ rescue Net::SMTPServerBusy, SystemCallError, OpenSSL::SSL::SSLError
409
+ # ignore SMTPServerBusy/EPIPE/ECONNRESET from Net::SMTP.start's ensure
410
+ end
411
+
412
+ ##
413
+ # Prepares ar_sendmail for exiting
414
+
415
+ def do_exit
416
+ log "caught signal, shutting down"
417
+ self.class.remove_pid_file
418
+ exit 130
419
+ end
420
+
421
+ ##
422
+ # Returns emails in email_class that haven't had a delivery attempt in the
423
+ # last 300 seconds.
424
+
425
+ def find_emails
426
+ options = { :conditions => ['last_send_attempt < ?', Time.now.to_i - 300], :order=>"priority desc" }
427
+ options[:limit] = batch_size unless batch_size.nil?
428
+ mail = ActionMailer::Base.email_class.find :all, options
429
+
430
+ log "found #{mail.length} emails to send"
431
+ mail
432
+ end
433
+
434
+ ##
435
+ # Installs signal handlers to gracefully exit.
436
+
437
+ def install_signal_handlers
438
+ trap 'TERM' do do_exit end
439
+ trap 'INT' do do_exit end
440
+ end
441
+
442
+ ##
443
+ # Logs +message+ if verbose
444
+
445
+ def log(message)
446
+ $stderr.puts message if @verbose
447
+ ActionMailer::Base.logger.info "ar_sendmail: #{message}"
448
+ end
449
+
450
+ ##
451
+ # Scans for emails and delivers them every delay seconds. Only returns if
452
+ # once is true.
453
+
454
+ def run
455
+ install_signal_handlers
456
+
457
+ loop do
458
+ begin
459
+ cleanup
460
+ emails = find_emails
461
+ deliver(emails) unless emails.empty?
462
+ rescue ActiveRecord::Transactions::TransactionError
463
+ end
464
+ break if @once
465
+ sleep @delay
466
+ end
467
+ end
468
+
469
+ ##
470
+ # Proxy to ActionMailer::Base::smtp_settings. See
471
+ # http://api.rubyonrails.org/classes/ActionMailer/Base.html
472
+ # for instructions on how to configure ActionMailer's SMTP server.
473
+ #
474
+ # Falls back to ::server_settings if ::smtp_settings doesn't exist for
475
+ # backwards compatibility.
476
+
477
+ def smtp_settings
478
+ ActionMailer::Base.smtp_settings rescue ActionMailer::Base.server_settings
479
+ end
480
+
481
+ end