adamcooper-ar_mailer 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ = 2.0.0
2
+
3
+ * Removed need to use ARMailer subclass. Just set the delivery method and you are ready to go. Backwards compatible with a deprecation notice if you subclass old ARMailer class.
4
+ * Only include SMTP TLS patch if Ruby version < 1.8.7 as it has an alternative. Changes based on Calvin Yu's [cyu] fork.
5
+ * Renamed default migration name to the modern Rails default
6
+ * Only authenticate if emails waiting to be sent
7
+ * Added --version switch to ar_sendmail binary
8
+ * Created a lighthouse account for this project (adzap fork only). See README.
9
+
10
+ = 1.4.4
11
+
12
+ * Exit init.d script with message if no mailers defined.
13
+
14
+ = 1.4.3
15
+
16
+ * Bugs fixed
17
+ * Replaced mistaken call to log when removing pid file artifact for
18
+ non-running daemon
19
+
20
+ = 1.4.2
21
+
22
+ * New Features
23
+ * Added Ruby based linux init.d script for handling daemon startup using yaml
24
+ config file. See files share/linux/ar_sendmail and ar_sendmail.conf
25
+ * Bugs fixed
26
+ * Proper handling for relative and absolute paths for the pid file
27
+ * Removed hoe dependency since we need the explicit gemspec file for github and
28
+ not deploying to RubyForge its not as useful.
29
+ * Moved old BSD rc.d script to share/bsd folder
30
+ * Updated README with github gem install, docs and init script info
31
+
32
+ = 1.4.1
33
+
34
+ * Bugs fixed
35
+ * Daemon failed on startup fixed with expanding full path of pid file
36
+
37
+ = 1.4.0
38
+
39
+ * Forked gem and published on GitHub (gem sources -a http://gems.github.com)
40
+ * New Features
41
+ * Added pid file creation on daemonize with command line option to specify pid filename [Dylan Egan]
42
+
43
+ = 1.3.1
44
+
45
+ * Fix bug #12530, gmail causes SSL errors. Submitted by Kyle Maxwell
46
+ and Alex Ostleitner.
47
+ * Try ActionMailer::Base::server_settings then ::smtp_settings. Fixes
48
+ bug #12516. Submitted by Alex Ostleitner.
49
+
50
+ = 1.3.0
51
+
52
+ * New Features
53
+ * Added automatic mail queue cleanup.
54
+ * MAY CAUSE LOSS OF DATA. If you haven't run ar_sendmail within
55
+ the expiry time, set it to 0.
56
+ * Bugs fixed
57
+ * Authentication errors are now handled by retrying once.
58
+
59
+ = 1.2.0
60
+
61
+ * Bugs fixed
62
+ * Handle SMTPServerBusy by backing off @delay seconds then re-queueing
63
+ * Allow email delivery class to be set in ARMailer.
64
+ * ar_sendmail --mailq works with --table-name now.
65
+ * Miscellaneous Updates
66
+ * Added documentation to require 'action_mailer/ar_mailer' in
67
+ instructions.
68
+ * Moved to ZSS p4 repository
69
+ * Supports TLS now. Requested by Dave Thomas. smtp_tls.rb from Kyle
70
+ Maxwell & etc.
71
+
72
+ = 1.1.0
73
+
74
+ * Features
75
+ * Added --chdir to set rails directory
76
+ * Added --environment to set RAILS_ENV
77
+ * Exits cleanly on TERM or INT signals
78
+ * Added FreeBSD rc.d script
79
+ * Exceptions during SMTP sending are now logged
80
+ * No longer waits if sending email took too long
81
+ * Bugs fixed
82
+ * Fixed last send attempt in --mailq
83
+ * Better SMTP error handling
84
+ * Messages are removed from the queue on 5xx errors
85
+ * Added Net::SMTP.reset to avoid needing to recreate the connection
86
+
87
+ = 1.0.1
88
+
89
+ * Bugs fixed
90
+ * From and to of email destination were swapped
91
+
92
+ = 1.0.0
93
+
94
+ * Birthday
@@ -0,0 +1,28 @@
1
+ Original code copyright 2006, 2007, Eric Hodel, The Robot Co-op. All
2
+ rights reserved. Some code under other license, see individual files
3
+ for details.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions
7
+ are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright
10
+ notice, this list of conditions and the following disclaimer.
11
+ 2. Redistributions in binary form must reproduce the above copyright
12
+ notice, this list of conditions and the following disclaimer in the
13
+ documentation and/or other materials provided with the distribution.
14
+ 3. Neither the names of the authors nor the names of their contributors
15
+ may be used to endorse or promote products derived from this software
16
+ without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
19
+ OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
+ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
22
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
23
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
24
+ OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
25
+ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
27
+ OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
28
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,15 @@
1
+ History.txt
2
+ LICENSE.txt
3
+ Manifest.txt
4
+ README.txt
5
+ Rakefile
6
+ bin/ar_sendmail
7
+ lib/action_mailer/ar_mailer.rb
8
+ lib/action_mailer/ar_sendmail.rb
9
+ lib/smtp_tls.rb
10
+ share/bsd/ar_sendmail
11
+ share/linux/ar_sendmail
12
+ share/linux/ar_sendmail.conf
13
+ test/action_mailer.rb
14
+ test/test_armailer.rb
15
+ test/test_arsendmail.rb
@@ -0,0 +1,124 @@
1
+ = ar_mailer
2
+
3
+ A two-phase delivery agent for ActionMailer
4
+
5
+ Rubyforge Project:
6
+
7
+ http://rubyforge.org/projects/seattlerb
8
+
9
+ Documentation:
10
+
11
+ http://seattlerb.org/ar_mailer
12
+
13
+ and for forked additions
14
+
15
+ http://github.com/adzap/ar_mailer/wikis
16
+
17
+ Bugs:
18
+
19
+ http://adzap.lighthouseapp.com/projects/26997-ar_mailer
20
+
21
+ == About
22
+
23
+ Even delivering email to the local machine may take too long when you have to
24
+ send hundreds of messages. ar_mailer allows you to store messages into the
25
+ database for later delivery by a separate process, ar_sendmail.
26
+
27
+ == Installing ar_mailer (forked)
28
+
29
+ Before installing you will need to make sure the original gem is uninstalled as they can't coexist:
30
+
31
+ $ sudo gem uninstall ar_mailer
32
+
33
+ Install the gem from GitHub gems server:
34
+
35
+ First, if you haven't already:
36
+
37
+ $ sudo gem sources -a http://gems.github.com
38
+
39
+ Then
40
+
41
+ $ sudo gem install adzap-ar_mailer
42
+
43
+ For Rails >= 2.1, in your environment.rb:
44
+
45
+ config.gem "adzap-ar_mailer", :lib => 'action_mailer/ar_mailer', :source => 'http://gems.github.com'
46
+
47
+ For Rails 2.0, in an initializer file:
48
+
49
+ require 'action_mailer/ar_mailer'
50
+
51
+ == Usage
52
+
53
+ Go to your Rails project:
54
+
55
+ $ cd your_rails_project
56
+
57
+ Create a new migration:
58
+
59
+ $ ar_sendmail --create-migration
60
+
61
+ You'll need to redirect this into a file. If you want a different name
62
+ provide the --table-name option.
63
+
64
+ Create a new model:
65
+
66
+ $ ar_sendmail --create-model
67
+
68
+ You'll need to redirect this into a file. If you want a different name
69
+ provide the --table-name option.
70
+
71
+ You'll need to be sure to set the From address for your emails. Something
72
+ like:
73
+
74
+ def list_send(recipient)
75
+ from 'no_reply@example.com'
76
+ # ...
77
+
78
+ Edit config/environments/production.rb and set the delivery method:
79
+
80
+ config.action_mailer.delivery_method = :activerecord
81
+
82
+ Or if you need to, you can set each mailer class delivery method individually:
83
+
84
+ class MyMailer < ActionMailer::Base
85
+ self.delivery_method = :activerecord
86
+ end
87
+
88
+ This can be useful when using plugins like ExceptionNotification. Where it
89
+ might be foolish to tie the sending of the email alert to the database when the
90
+ database might be causing the exception being raised. In this instance you could
91
+ override ExceptionNofitier delivery method to be smtp or set the other
92
+ mailer classes to use ARMailer explicitly.
93
+
94
+ Then to run it:
95
+
96
+ $ ar_sendmail
97
+
98
+ You can also run it from cron with -o, or as a daemon with -d.
99
+
100
+ See <tt>ar_sendmail -h</tt> for full details.
101
+
102
+ === Alternate Mail Storage
103
+
104
+ If you want to set the ActiveRecord model that emails will be stored in,
105
+ see ActionMailer::Base.email_class=
106
+
107
+
108
+ === Help
109
+
110
+ See ar_sendmail -h for options to ar_sendmail.
111
+
112
+ NOTE: You may need to delete an smtp_tls.rb file if you have one lying
113
+ around. ar_mailer supplies it own.
114
+
115
+ == Run as a service (init.d/rc.d scripts)
116
+
117
+ For Linux both script and demo config files are in share/linux.
118
+ See ar_sendmail.conf for setting up your config. Copy the ar_sendmail file
119
+ to /etc/init.d/ and make it executable. Then for Debian based distros run
120
+ 'sudo update-rc.d ar_sendmail defaults' and it should work. Make sure you have
121
+ the config file /etc/ar_sendmail.conf in place before starting.
122
+
123
+ For FreeBSD or NetBSD script is share/bsd/ar_sendmail. This is old and does not
124
+ support the config file unless someone wants to submit a patch.
@@ -0,0 +1,58 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+ require 'rake/testtask'
4
+ require 'rake/rdoctask'
5
+
6
+ $:.unshift(File.expand_path(File.dirname(__FILE__) + '/lib'))
7
+
8
+ require './lib/action_mailer/ar_sendmail'
9
+
10
+ ar_mailer_gemspec = Gem::Specification.new do |s|
11
+ s.name = %q{ar_mailer}
12
+ s.version = ActionMailer::ARSendmail::VERSION
13
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
14
+ s.authors = ["Eric Hodel", "Adam Meehan"]
15
+ s.default_executable = %q{ar_sendmail}
16
+ s.description = %q{Even delivering email to the local machine may take too long when you have to send hundreds of messages. ar_mailer allows you to store messages into the database for later delivery by a separate process, ar_sendmail.}
17
+ s.email = %q{adam.meehan@gmail.com}
18
+ s.executables = ["ar_sendmail"]
19
+ s.extra_rdoc_files = ["History.txt", "LICENSE.txt", "Manifest.txt", "README.rdoc"]
20
+ s.files = ["History.txt", "LICENSE.txt", "Manifest.txt", "README.rdoc", "Rakefile", "bin/ar_sendmail", "lib/action_mailer/ar_mailer.rb", "lib/action_mailer/ar_sendmail.rb", "lib/smtp_tls.rb", "share/bsd/ar_sendmail", "share/linux/ar_sendmail", "share/linux/ar_sendmail.conf", "test/action_mailer.rb", "test/test_armailer.rb", "test/test_arsendmail.rb"]
21
+ s.has_rdoc = true
22
+ s.homepage = %q{http://github.com/adzap/ar_mailer}
23
+ s.rdoc_options = ["--main", "README.rdoc"]
24
+ s.require_paths = ["lib"]
25
+ s.rubyforge_project = %q{seattlerb}
26
+ s.summary = %q{A two-phase delivery agent for ActionMailer}
27
+ s.test_files = ["test/test_armailer.rb", "test/test_arsendmail.rb"]
28
+ end
29
+
30
+ Rake::GemPackageTask.new(ar_mailer_gemspec) do |pkg|
31
+ pkg.gem_spec = ar_mailer_gemspec
32
+ end
33
+
34
+ namespace :gem do
35
+ namespace :spec do
36
+ desc "Update ar_mailer.gemspec"
37
+ task :generate do
38
+ File.open("ar_mailer.gemspec", "w") do |f|
39
+ f.puts(ar_mailer_gemspec.to_ruby)
40
+ end
41
+ end
42
+ end
43
+ end
44
+
45
+ desc "Build packages and install"
46
+ task :install => :package do
47
+ sh %{sudo gem install --local pkg/ar_mailer-#{ActionMailer::ARSendmail::VERSION}}
48
+ end
49
+
50
+ desc 'Default: run unit tests.'
51
+ task :default => :test
52
+
53
+ desc 'Test the ar_mailer gem.'
54
+ Rake::TestTask.new(:test) do |t|
55
+ t.libs << 'lib' << 'test'
56
+ t.pattern = 'test/**/test_*.rb'
57
+ t.verbose = true
58
+ end
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'action_mailer/ar_sendmail'
4
+
5
+ ActionMailer::ARSendmail.run
6
+
@@ -0,0 +1,47 @@
1
+ require 'action_mailer'
2
+
3
+ ##
4
+ # Adds sending email through an ActiveRecord table as a delivery method for
5
+ # ActionMailer.
6
+ #
7
+
8
+ class ActionMailer::ARMailer < ActionMailer::Base
9
+
10
+ def self.inherited(sub)
11
+ logger.warn('The ActionMailer::ARMailer class has been deprecated. Will be removed in version 2.1. Just use ActionMailer::Base.')
12
+ end
13
+
14
+ end
15
+
16
+ class ActionMailer::Base
17
+
18
+ @@email_class = :Email
19
+
20
+ ##
21
+ # Current email class for deliveries.
22
+
23
+ def self.email_class
24
+ Object.const_get(@@email_class)
25
+ end
26
+
27
+ ##
28
+ # Sets the email class for deliveries.
29
+
30
+ def self.email_class=(klass)
31
+ @@email_class = klass
32
+ end
33
+
34
+ ##
35
+ # Adds +mail+ to the Email table. Only the first From address for +mail+ is
36
+ # used.
37
+
38
+ def perform_delivery_activerecord(mail)
39
+ email_class = self.class.email_class
40
+ mail.destinations.each do |destination|
41
+ email_class.create :mail => mail.encoded, :to => destination,
42
+ :from => mail.from.first
43
+ end
44
+ end
45
+
46
+ end
47
+
@@ -0,0 +1,567 @@
1
+ require 'optparse'
2
+ require 'net/smtp'
3
+ require 'smtp_tls' unless Net::SMTP.instance_methods.include?("enable_starttls_auto")
4
+ require 'rubygems'
5
+
6
+ class Object # :nodoc:
7
+ unless respond_to? :path2class then
8
+ def self.path2class(path)
9
+ path.split(/::/).inject self do |k,n| k.const_get n end
10
+ end
11
+ end
12
+ end
13
+
14
+ ##
15
+ # Hack in RSET
16
+
17
+ module Net # :nodoc:
18
+ class SMTP # :nodoc:
19
+
20
+ unless instance_methods.include? 'reset' then
21
+ ##
22
+ # Resets the SMTP connection.
23
+
24
+ def reset
25
+ getok 'RSET'
26
+ end
27
+ end
28
+
29
+ end
30
+ end
31
+
32
+ module ActionMailer; end # :nodoc:
33
+
34
+ ##
35
+ # ActionMailer::ARSendmail delivers email from the email table to the
36
+ # SMTP server configured in your application's config/environment.rb.
37
+ # ar_sendmail does not work with sendmail delivery.
38
+ #
39
+ # ar_mailer can deliver to SMTP with TLS using smtp_tls.rb borrowed from Kyle
40
+ # Maxwell's action_mailer_optional_tls plugin. Simply set the :tls option in
41
+ # ActionMailer::Base's smtp_settings to true to enable TLS.
42
+ #
43
+ # See ar_sendmail -h for the full list of supported options.
44
+ #
45
+ # The interesting options are:
46
+ # * --daemon
47
+ # * --mailq
48
+ # * --create-migration
49
+ # * --create-model
50
+ # * --table-name
51
+
52
+ class ActionMailer::ARSendmail
53
+
54
+ ##
55
+ # The version of ActionMailer::ARSendmail you are running.
56
+
57
+ VERSION = '2.0.2'
58
+
59
+ ##
60
+ # Maximum number of times authentication will be consecutively retried
61
+
62
+ MAX_AUTH_FAILURES = 2
63
+
64
+ ##
65
+ # Email delivery attempts per run
66
+
67
+ attr_accessor :batch_size
68
+
69
+ ##
70
+ # Seconds to delay between runs
71
+
72
+ attr_accessor :delay
73
+
74
+ ##
75
+ # Maximum age of emails in seconds before they are removed from the queue.
76
+
77
+ attr_accessor :max_age
78
+
79
+ ##
80
+ # Be verbose
81
+
82
+ attr_accessor :verbose
83
+
84
+ ##
85
+ # ActiveRecord class that holds emails
86
+
87
+ attr_reader :email_class
88
+
89
+ ##
90
+ # True if only one delivery attempt will be made per call to run
91
+
92
+ attr_reader :once
93
+
94
+ ##
95
+ # Times authentication has failed
96
+
97
+ attr_accessor :failed_auth_count
98
+
99
+ @@pid_file = nil
100
+
101
+ def self.remove_pid_file
102
+ if @@pid_file
103
+ require 'shell'
104
+ sh = Shell.new
105
+ sh.rm @@pid_file
106
+ end
107
+ end
108
+
109
+ ##
110
+ # Creates a new migration using +table_name+ and prints it on stdout.
111
+
112
+ def self.create_migration(table_name)
113
+ require 'active_support'
114
+ puts <<-EOF
115
+ class Create#{table_name.classify} < ActiveRecord::Migration
116
+ def self.up
117
+ create_table :#{table_name.tableize} do |t|
118
+ t.column :from, :string
119
+ t.column :to, :string
120
+ t.column :last_send_attempt, :integer, :default => 0
121
+ t.column :mail, :text
122
+ t.column :created_on, :datetime
123
+ end
124
+ end
125
+
126
+ def self.down
127
+ drop_table :#{table_name.tableize}
128
+ end
129
+ end
130
+ EOF
131
+ end
132
+
133
+ ##
134
+ # Creates a new model using +table_name+ and prints it on stdout.
135
+
136
+ def self.create_model(table_name)
137
+ require 'active_support'
138
+ puts <<-EOF
139
+ class #{table_name.classify} < ActiveRecord::Base
140
+ end
141
+ EOF
142
+ end
143
+
144
+ ##
145
+ # Prints a list of unsent emails and the last delivery attempt, if any.
146
+ #
147
+ # If ActiveRecord::Timestamp is not being used the arrival time will not be
148
+ # known. See http://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html
149
+ # to learn how to enable ActiveRecord::Timestamp.
150
+
151
+ def self.mailq(table_name)
152
+ klass = table_name.split('::').inject(Object) { |k,n| k.const_get n }
153
+ emails = klass.find :all
154
+
155
+ if emails.empty? then
156
+ puts "Mail queue is empty"
157
+ return
158
+ end
159
+
160
+ total_size = 0
161
+
162
+ puts "-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------"
163
+ emails.each do |email|
164
+ size = email.mail.length
165
+ total_size += size
166
+
167
+ create_timestamp = email.created_on rescue
168
+ email.created_at rescue
169
+ Time.at(email.created_date) rescue # for Robot Co-op
170
+ nil
171
+
172
+ created = if create_timestamp.nil? then
173
+ ' Unknown'
174
+ else
175
+ create_timestamp.strftime '%a %b %d %H:%M:%S'
176
+ end
177
+
178
+ puts "%10d %8d %s %s" % [email.id, size, created, email.from]
179
+ if email.last_send_attempt > 0 then
180
+ puts "Last send attempt: #{Time.at email.last_send_attempt}"
181
+ end
182
+ puts " #{email.to}"
183
+ puts
184
+ end
185
+
186
+ puts "-- #{total_size/1024} Kbytes in #{emails.length} Requests."
187
+ end
188
+
189
+ ##
190
+ # Processes command line options in +args+
191
+
192
+ def self.process_args(args)
193
+ name = File.basename $0
194
+
195
+ options = {}
196
+ options[:Chdir] = '.'
197
+ options[:Daemon] = false
198
+ options[:Delay] = 60
199
+ options[:MaxAge] = 86400 * 7
200
+ options[:Once] = false
201
+ options[:RailsEnv] = ENV['RAILS_ENV']
202
+ options[:TableName] = 'Email'
203
+ options[:Pidfile] = options[:Chdir] + '/log/ar_sendmail.pid'
204
+
205
+ opts = OptionParser.new do |opts|
206
+ opts.banner = "Usage: #{name} [options]"
207
+ opts.separator ''
208
+
209
+ opts.separator "#{name} scans the email table for new messages and sends them to the"
210
+ opts.separator "website's configured SMTP host."
211
+ opts.separator ''
212
+ opts.separator "#{name} must be run from a Rails application's root."
213
+
214
+ opts.separator ''
215
+ opts.separator 'Sendmail options:'
216
+
217
+ opts.on("-b", "--batch-size BATCH_SIZE",
218
+ "Maximum number of emails to send per delay",
219
+ "Default: Deliver all available emails", Integer) do |batch_size|
220
+ options[:BatchSize] = batch_size
221
+ end
222
+
223
+ opts.on( "--delay DELAY",
224
+ "Delay between checks for new mail",
225
+ "in the database",
226
+ "Default: #{options[:Delay]}", Integer) do |delay|
227
+ options[:Delay] = delay
228
+ end
229
+
230
+ opts.on( "--max-age MAX_AGE",
231
+ "Maxmimum age for an email. After this",
232
+ "it will be removed from the queue.",
233
+ "Set to 0 to disable queue cleanup.",
234
+ "Default: #{options[:MaxAge]} seconds", Integer) do |max_age|
235
+ options[:MaxAge] = max_age
236
+ end
237
+
238
+ opts.on("-o", "--once",
239
+ "Only check for new mail and deliver once",
240
+ "Default: #{options[:Once]}") do |once|
241
+ options[:Once] = once
242
+ end
243
+
244
+ opts.on("-d", "--daemonize",
245
+ "Run as a daemon process",
246
+ "Default: #{options[:Daemon]}") do |daemon|
247
+ options[:Daemon] = true
248
+ end
249
+
250
+ opts.on("-p", "--pidfile PIDFILE",
251
+ "Set the pidfile location",
252
+ "Default: #{options[:Chdir]}#{options[:Pidfile]}", String) do |pidfile|
253
+ options[:Pidfile] = pidfile
254
+ end
255
+
256
+ opts.on( "--mailq",
257
+ "Display a list of emails waiting to be sent") do |mailq|
258
+ options[:MailQ] = true
259
+ end
260
+
261
+ opts.separator ''
262
+ opts.separator 'Setup Options:'
263
+
264
+ opts.on( "--create-migration",
265
+ "Prints a migration to add an Email table",
266
+ "to stdout") do |create|
267
+ options[:Migrate] = true
268
+ end
269
+
270
+ opts.on( "--create-model",
271
+ "Prints a model for an Email ActiveRecord",
272
+ "object to stdout") do |create|
273
+ options[:Model] = true
274
+ end
275
+
276
+ opts.separator ''
277
+ opts.separator 'Generic Options:'
278
+
279
+ opts.on("-c", "--chdir PATH",
280
+ "Use PATH for the application path",
281
+ "Default: #{options[:Chdir]}") do |path|
282
+ usage opts, "#{path} is not a directory" unless File.directory? path
283
+ usage opts, "#{path} is not readable" unless File.readable? path
284
+ options[:Chdir] = path
285
+ end
286
+
287
+ opts.on("-e", "--environment RAILS_ENV",
288
+ "Set the RAILS_ENV constant",
289
+ "Default: #{options[:RailsEnv]}") do |env|
290
+ options[:RailsEnv] = env
291
+ end
292
+
293
+ opts.on("-t", "--table-name TABLE_NAME",
294
+ "Name of table holding emails",
295
+ "Used for both sendmail and",
296
+ "migration creation",
297
+ "Default: #{options[:TableName]}") do |name|
298
+ options[:TableName] = name
299
+ end
300
+
301
+ opts.on("-v", "--[no-]verbose",
302
+ "Be verbose",
303
+ "Default: #{options[:Verbose]}") do |verbose|
304
+ options[:Verbose] = verbose
305
+ end
306
+
307
+ opts.on("-h", "--help",
308
+ "You're looking at it") do
309
+ usage opts
310
+ end
311
+
312
+ opts.on("--version", "Version of ARMailer") do
313
+ usage "ar_mailer #{VERSION} (adzap fork)"
314
+ end
315
+
316
+ opts.separator ''
317
+ end
318
+
319
+ opts.parse! args
320
+
321
+ return options if options.include? :Migrate or options.include? :Model
322
+
323
+ ENV['RAILS_ENV'] = options[:RailsEnv]
324
+
325
+ Dir.chdir options[:Chdir] do
326
+ begin
327
+ require 'config/environment'
328
+ rescue LoadError
329
+ usage opts, <<-EOF
330
+ #{name} must be run from a Rails application's root to deliver email.
331
+ #{Dir.pwd} does not appear to be a Rails application root.
332
+ EOF
333
+ end
334
+ end
335
+
336
+ return options
337
+ end
338
+
339
+ ##
340
+ # Processes +args+ and runs as appropriate
341
+
342
+ def self.run(args = ARGV)
343
+ options = process_args args
344
+
345
+ if options.include? :Migrate then
346
+ create_migration options[:TableName]
347
+ exit
348
+ elsif options.include? :Model then
349
+ create_model options[:TableName]
350
+ exit
351
+ elsif options.include? :MailQ then
352
+ mailq options[:TableName]
353
+ exit
354
+ end
355
+
356
+ if options[:Daemon] then
357
+ require 'webrick/server'
358
+ @@pid_file = File.expand_path(options[:Pidfile], options[:Chdir])
359
+ if File.exists? @@pid_file
360
+ # check to see if process is actually running
361
+ pid = ''
362
+ File.open(@@pid_file, 'r') {|f| pid = f.read.chomp }
363
+ if system("ps -p #{pid} | grep #{pid}") # returns true if process is running, o.w. false
364
+ $stderr.puts "Warning: The pid file #{@@pid_file} exists and ar_sendmail is running. Shutting down."
365
+ exit
366
+ else
367
+ # not running, so remove existing pid file and continue
368
+ self.remove_pid_file
369
+ $stderr.puts "ar_sendmail is not running. Removing existing pid file and starting up..."
370
+ end
371
+ end
372
+ WEBrick::Daemon.start
373
+ File.open(@@pid_file, 'w') {|f| f.write("#{Process.pid}\n")}
374
+ end
375
+
376
+ new(options).run
377
+
378
+ rescue SystemExit
379
+ raise
380
+ rescue SignalException
381
+ exit
382
+ rescue Exception => e
383
+ $stderr.puts "Unhandled exception #{e.message}(#{e.class}):"
384
+ $stderr.puts "\t#{e.backtrace.join "\n\t"}"
385
+ exit 1
386
+ end
387
+
388
+ ##
389
+ # Prints a usage message to $stderr using +opts+ and exits
390
+
391
+ def self.usage(opts, message = nil)
392
+ if message then
393
+ $stderr.puts message
394
+ $stderr.puts
395
+ end
396
+
397
+ $stderr.puts opts
398
+ exit 1
399
+ end
400
+
401
+ ##
402
+ # Creates a new ARSendmail.
403
+ #
404
+ # Valid options are:
405
+ # <tt>:BatchSize</tt>:: Maximum number of emails to send per delay
406
+ # <tt>:Delay</tt>:: Delay between deliver attempts
407
+ # <tt>:TableName</tt>:: Table name that stores the emails
408
+ # <tt>:Once</tt>:: Only attempt to deliver emails once when run is called
409
+ # <tt>:Verbose</tt>:: Be verbose.
410
+
411
+ def initialize(options = {})
412
+ options[:Delay] ||= 60
413
+ options[:TableName] ||= 'Email'
414
+ options[:MaxAge] ||= 86400 * 7
415
+
416
+ @batch_size = options[:BatchSize]
417
+ @delay = options[:Delay]
418
+ @email_class = Object.path2class options[:TableName]
419
+ @once = options[:Once]
420
+ @verbose = options[:Verbose]
421
+ @max_age = options[:MaxAge]
422
+
423
+ @failed_auth_count = 0
424
+ end
425
+
426
+ ##
427
+ # Removes emails that have lived in the queue for too long. If max_age is
428
+ # set to 0, no emails will be removed.
429
+
430
+ def cleanup
431
+ return if @max_age == 0
432
+ timeout = Time.now - @max_age
433
+ conditions = ['last_send_attempt > 0 and created_on < ?', timeout]
434
+ mail = @email_class.destroy_all conditions
435
+
436
+ log "expired #{mail.length} emails from the queue"
437
+ end
438
+
439
+ ##
440
+ # Delivers +emails+ to ActionMailer's SMTP server and destroys them.
441
+
442
+ def deliver(emails)
443
+ settings = [
444
+ smtp_settings[:domain],
445
+ (smtp_settings[:user] || smtp_settings[:user_name]),
446
+ smtp_settings[:password],
447
+ smtp_settings[:authentication]
448
+ ]
449
+
450
+ smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
451
+ if smtp.respond_to?(:enable_starttls_auto)
452
+ smtp.enable_starttls_auto
453
+ else
454
+ settings << smtp_settings[:tls]
455
+ end
456
+
457
+ smtp.start(*settings) do |session|
458
+ @failed_auth_count = 0
459
+ until emails.empty? do
460
+ email = emails.shift
461
+ begin
462
+ res = session.send_message email.mail, email.from, email.to
463
+ email.destroy
464
+ log "sent email %011d from %s to %s: %p" %
465
+ [email.id, email.from, email.to, res]
466
+ rescue Net::SMTPFatalError => e
467
+ log "5xx error sending email %d, removing from queue: %p(%s):\n\t%s" %
468
+ [email.id, e.message, e.class, e.backtrace.join("\n\t")]
469
+ email.destroy
470
+ session.reset
471
+ rescue Net::SMTPServerBusy => e
472
+ log "server too busy, sleeping #{@delay} seconds"
473
+ sleep delay
474
+ return
475
+ rescue Net::SMTPUnknownError, Net::SMTPSyntaxError, TimeoutError => e
476
+ email.last_send_attempt = Time.now.to_i
477
+ email.save rescue nil
478
+ log "error sending email %d: %p(%s):\n\t%s" %
479
+ [email.id, e.message, e.class, e.backtrace.join("\n\t")]
480
+ session.reset
481
+ end
482
+ end
483
+ end
484
+ rescue Net::SMTPAuthenticationError => e
485
+ @failed_auth_count += 1
486
+ if @failed_auth_count >= MAX_AUTH_FAILURES then
487
+ log "authentication error, giving up: #{e.message}"
488
+ raise e
489
+ else
490
+ log "authentication error, retrying: #{e.message}"
491
+ end
492
+ sleep delay
493
+ rescue Net::SMTPServerBusy, SystemCallError, OpenSSL::SSL::SSLError
494
+ # ignore SMTPServerBusy/EPIPE/ECONNRESET from Net::SMTP.start's ensure
495
+ end
496
+
497
+ ##
498
+ # Prepares ar_sendmail for exiting
499
+
500
+ def do_exit
501
+ log "caught signal, shutting down"
502
+ self.class.remove_pid_file
503
+ exit
504
+ end
505
+
506
+ ##
507
+ # Returns emails in email_class that haven't had a delivery attempt in the
508
+ # last 300 seconds.
509
+
510
+ def find_emails
511
+ options = { :conditions => ['last_send_attempt < ?', Time.now.to_i - 300] }
512
+ options[:limit] = batch_size unless batch_size.nil?
513
+ mail = @email_class.find :all, options
514
+
515
+ log "found #{mail.length} emails to send"
516
+ mail
517
+ end
518
+
519
+ ##
520
+ # Installs signal handlers to gracefully exit.
521
+
522
+ def install_signal_handlers
523
+ trap 'TERM' do do_exit end
524
+ trap 'INT' do do_exit end
525
+ end
526
+
527
+ ##
528
+ # Logs +message+ if verbose
529
+
530
+ def log(message)
531
+ $stderr.puts message if @verbose
532
+ ActionMailer::Base.logger.info "ar_sendmail: #{message}"
533
+ end
534
+
535
+ ##
536
+ # Scans for emails and delivers them every delay seconds. Only returns if
537
+ # once is true.
538
+
539
+ def run
540
+ install_signal_handlers
541
+
542
+ loop do
543
+ now = Time.now
544
+ begin
545
+ cleanup
546
+ emails = find_emails
547
+ deliver(emails) unless emails.empty?
548
+ rescue ActiveRecord::Transactions::TransactionError
549
+ end
550
+ break if @once
551
+ sleep @delay if now + @delay > Time.now
552
+ end
553
+ end
554
+
555
+ ##
556
+ # Proxy to ActionMailer::Base::smtp_settings. See
557
+ # http://api.rubyonrails.org/classes/ActionMailer/Base.html
558
+ # for instructions on how to configure ActionMailer's SMTP server.
559
+ #
560
+ # Falls back to ::server_settings if ::smtp_settings doesn't exist for
561
+ # backwards compatibility.
562
+
563
+ def smtp_settings
564
+ ActionMailer::Base.smtp_settings rescue ActionMailer::Base.server_settings
565
+ end
566
+
567
+ end