Class: ActionMailer::ARSendmail
- Inherits:
-
Object
- Object
- ActionMailer::ARSendmail
- Defined in:
- lib/action_mailer/ar_sendmail.rb
Constant Summary collapse
- VERSION =
The version of ActionMailer::ARSendmail you are running.
'2.1.5'
- MAX_AUTH_FAILURES =
Maximum number of times authentication will be consecutively retried
2
- @@pid_file =
nil
Instance Attribute Summary collapse
-
#batch_size ⇒ Object
Email delivery attempts per run.
-
#delay ⇒ Object
Seconds to delay between runs.
-
#failed_auth_count ⇒ Object
Times authentication has failed.
-
#max_age ⇒ Object
Maximum age of emails in seconds before they are removed from the queue.
-
#once ⇒ Object
readonly
True if only one delivery attempt will be made per call to run.
-
#verbose ⇒ Object
Be verbose.
Class Method Summary collapse
-
.digest_error_emails(options = {}) ⇒ Object
Packs non-digested messages into digests, and send them options: (see default values in first lines of code) :dump_path - dir in which to dump full digest message in case it needs to be truncated.
-
.mailq ⇒ Object
Prints a list of unsent emails and the last delivery attempt, if any.
-
.process_args(args) ⇒ Object
Processes command line options in
args
. - .remove_pid_file ⇒ Object
-
.run(args = ARGV) ⇒ Object
Processes
args
and runs as appropriate. -
.usage(opts, message = nil) ⇒ Object
Prints a usage message to $stderr using
opts
and exits.
Instance Method Summary collapse
-
#cleanup ⇒ Object
Removes emails that have lived in the queue for too long.
-
#deliver(emails) ⇒ Object
Delivers
emails
to ActionMailer’s SMTP server and destroys them. - #deliver_emails ⇒ Object
-
#do_exit ⇒ Object
Prepares ar_sendmail for exiting.
-
#find_emails ⇒ Object
Returns emails in email_class that haven’t had a delivery attempt in the last 300 seconds.
-
#initialize(options = {}) ⇒ ARSendmail
constructor
Creates a new ARSendmail.
-
#install_signal_handlers ⇒ Object
Installs signal handlers to gracefully exit.
-
#log(message) ⇒ Object
Logs
message
if verbose. -
#run ⇒ Object
Scans for emails and delivers them every delay seconds.
-
#smtp_settings ⇒ Object
Proxy to ActionMailer::Base::smtp_settings.
Constructor Details
#initialize(options = {}) ⇒ ARSendmail
Creates a new ARSendmail.
Valid options are:
:BatchSize
-
Maximum number of emails to send per delay
:Delay
-
Delay between deliver attempts
:Once
-
Only attempt to deliver emails once when run is called
:Verbose
-
Be verbose.
331 332 333 334 335 336 337 338 339 340 341 342 343 |
# File 'lib/action_mailer/ar_sendmail.rb', line 331 def initialize( = {}) [:Delay] ||= 60 [:MaxAge] ||= 86400 * 7 @batch_size = [:BatchSize] @delay = [:Delay] @once = [:Once] @verbose = [:Verbose] @max_age = [:MaxAge] @smtp_settings = [:smtp_settings] @failed_auth_count = 0 end |
Instance Attribute Details
#batch_size ⇒ Object
Email delivery attempts per run
56 57 58 |
# File 'lib/action_mailer/ar_sendmail.rb', line 56 def batch_size @batch_size end |
#delay ⇒ Object
Seconds to delay between runs
61 62 63 |
# File 'lib/action_mailer/ar_sendmail.rb', line 61 def delay @delay end |
#failed_auth_count ⇒ Object
Times authentication has failed
82 83 84 |
# File 'lib/action_mailer/ar_sendmail.rb', line 82 def failed_auth_count @failed_auth_count end |
#max_age ⇒ Object
Maximum age of emails in seconds before they are removed from the queue.
66 67 68 |
# File 'lib/action_mailer/ar_sendmail.rb', line 66 def max_age @max_age end |
#once ⇒ Object (readonly)
True if only one delivery attempt will be made per call to run
77 78 79 |
# File 'lib/action_mailer/ar_sendmail.rb', line 77 def once @once end |
#verbose ⇒ Object
Be verbose
71 72 73 |
# File 'lib/action_mailer/ar_sendmail.rb', line 71 def verbose @verbose end |
Class Method Details
.digest_error_emails(options = {}) ⇒ Object
Packs non-digested messages into digests, and send them options: (see default values in first lines of code)
:dump_path - dir in which to dump full digest message in case it needs to be truncated.
:subj_prefix - specifies subject prefix that is already set to all the messages. If it's specified it's removed from subjects when combining them into digest's subject.
:max_subj_size - maximum subject size of digest email
:mail_body_size_limit - maximum body size of digest email
:smtp_settings - what smtp settings to use. Hash is expected described in http://api.rubyonrails.org/classes/ActionMailer/Base.html, +setting :tls to false will work. If omitted asks it from #smtp_settings method
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
# File 'lib/action_mailer/ar_sendmail.rb', line 498 def self.digest_error_emails( = {}) .reverse_merge! :dump_path => 'log', :max_subj_size => 150, :mail_body_size_limit => 1.megabyte subj_prefix = [:subj_prefix] max_subj_size = [:max_subj_size] mail_body_size_limit = [:mail_body_size_limit] email_class = ActionMailer::Base.email_class #Email.count(:group => :to) doesn't work because to is reserved word in MySQL counts = email_class.connection.select_rows("select `to`, count(*) AS count_all FROM `emails` where !ready GROUP BY `to`") counts.each do |to, count| if count.to_i == 1 email_class.update_all(['ready = ?', true], ['`to` = ?', to]) next end subjects = [] mails = [] from = nil email_class.transaction do emails = email_class.find(:all, :conditions => {:to => to, :ready => false}, :order => 'created_on') msg = nil email = nil last_date = nil emails.each do |email| msg = TMail::Mail.parse(email.mail) subject = msg.subject subject = subject[subj_prefix.length..-1] if subject.starts_with?(subj_prefix) subjects << subject mail = msg.header.select {|key, value| ['date', 'from', 'subject'].include?(key)}. map {|key, value| '%s: %s' % [key.capitalize, value.to_s]}.join("\n") mail += "\n\n" + msg.body mails << mail from = msg.header['from'].to_s last_date = msg.date email.destroy end new = TMail::Mail.new new.to = to new.from = from subject = subj_prefix + subjects.uniq.join("; ") new.subject = subject.size > max_subj_size ? subject[0..max_subj_size] + '... (and more)' : subject new.mime_version = msg.mime_version new.content_type = "text/plain" #this code doesn't really support anything else new.charset = msg.charset new.date = last_date splitter = "\n" + '=' * 70 + "\n" body = splitter + mails.join(splitter) if body.size > mail_body_size_limit email_dump_path = [:dump_path] + "/err.emails.#{Time.now.to_i}" File.open(email_dump_path, 'w') do |f| f.write(body) end old_size = body.size body = body[0..mail_body_size_limit] #yeah it will be bit more considering the header, but we don't care new_num = body.split(splitter).size body = ("WARNING: not all the messages made it into this digest - some are lost in truncation. " + "Original number of messages - #{mails.size} (here only #{new_num}); original size - #{old_size} " + "(here only #{body.size}). Full dump of original emails is placed in #{email_dump_path} @#{`hostname`.strip}.\n\n") + body end new.body = body email = email_class.create!(:from => email.from, :to => to, :mail => new.to_s, :ready => true) end end self.new(:smtp_settings => [:smtp_settings]).deliver_emails end |
.mailq ⇒ Object
Prints a list of unsent emails and the last delivery attempt, if any.
If ActiveRecord::Timestamp is not being used the arrival time will not be known. See api.rubyonrails.org/classes/ActiveRecord/Timestamp.html to learn how to enable ActiveRecord::Timestamp.
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 |
# File 'lib/action_mailer/ar_sendmail.rb', line 101 def self.mailq emails = ActionMailer::Base.email_class.find :all if emails.empty? then puts "Mail queue is empty" return end total_size = 0 puts "-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------" emails.each do |email| size = email.mail.length total_size += size = email.created_on rescue email.created_at rescue Time.at(email.created_date) rescue # for Robot Co-op nil created = if .nil? then ' Unknown' else .strftime '%a %b %d %H:%M:%S' end puts "%10d %8d %s %s" % [email.id, size, created, email.from] if email.last_send_attempt > 0 then puts "Last send attempt: #{Time.at email.last_send_attempt}" end puts " #{email.to}" puts end puts "-- #{total_size/1024} Kbytes in #{emails.length} Requests." end |
.process_args(args) ⇒ Object
Processes command line options in args
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 |
# File 'lib/action_mailer/ar_sendmail.rb', line 141 def self.process_args(args) name = File.basename $0 = {} [:Chdir] = '.' [:Daemon] = false [:Delay] = 60 [:MaxAge] = 86400 * 7 [:Once] = false [:RailsEnv] = ENV['RAILS_ENV'] [:Pidfile] = [:Chdir] + '/log/ar_sendmail.pid' opts = OptionParser.new do |opts| opts. = "Usage: #{name} [options]" opts.separator '' opts.separator "#{name} scans the email table for new messages and sends them to the" opts.separator "website's configured SMTP host." opts.separator '' opts.separator "#{name} must be run from a Rails application's root." opts.separator '' opts.separator 'Sendmail options:' opts.on("-b", "--batch-size BATCH_SIZE", "Maximum number of emails to send per delay", "Default: Deliver all available emails", Integer) do |batch_size| [:BatchSize] = batch_size end opts.on( "--delay DELAY", "Delay between checks for new mail", "in the database", "Default: #{[:Delay]}", Integer) do |delay| [:Delay] = delay end opts.on( "--max-age MAX_AGE", "Maxmimum age for an email. After this", "it will be removed from the queue.", "Set to 0 to disable queue cleanup.", "Default: #{[:MaxAge]} seconds", Integer) do |max_age| [:MaxAge] = max_age end opts.on("-o", "--once", "Only check for new mail and deliver once", "Default: #{[:Once]}") do |once| [:Once] = once end opts.on("-d", "--daemonize", "Run as a daemon process", "Default: #{[:Daemon]}") do |daemon| [:Daemon] = true end opts.on("-p", "--pidfile PIDFILE", "Set the pidfile location", "Default: #{[:Chdir]}#{[:Pidfile]}", String) do |pidfile| [:Pidfile] = pidfile end opts.on( "--mailq", "Display a list of emails waiting to be sent") do |mailq| [:MailQ] = true end opts.separator '' opts.separator 'Setup Options:' opts.separator '' opts.separator 'Generic Options:' opts.on("-c", "--chdir PATH", "Use PATH for the application path", "Default: #{[:Chdir]}") do |path| usage opts, "#{path} is not a directory" unless File.directory? path usage opts, "#{path} is not readable" unless File.readable? path [:Chdir] = path end opts.on("-e", "--environment RAILS_ENV", "Set the RAILS_ENV constant", "Default: #{[:RailsEnv]}") do |env| [:RailsEnv] = env end opts.on("-v", "--[no-]verbose", "Be verbose", "Default: #{[:Verbose]}") do |verbose| [:Verbose] = verbose end opts.on("-h", "--help", "You're looking at it") do usage opts end opts.on("--version", "Version of ARMailer") do usage "ar_mailer #{VERSION} (adzap fork)" end opts.separator '' end opts.parse! args ENV['RAILS_ENV'] = [:RailsEnv] Dir.chdir [:Chdir] do begin require 'config/environment' require 'action_mailer/ar_mailer' rescue LoadError usage opts, <<-EOF #{name} must be run from a Rails application's root to deliver email. #{Dir.pwd} does not appear to be a Rails application root. EOF end end return end |
.remove_pid_file ⇒ Object
86 87 88 89 90 91 92 |
# File 'lib/action_mailer/ar_sendmail.rb', line 86 def self.remove_pid_file if @@pid_file require 'shell' sh = Shell.new sh.rm @@pid_file end end |
.run(args = ARGV) ⇒ Object
Processes args
and runs as appropriate
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 |
# File 'lib/action_mailer/ar_sendmail.rb', line 269 def self.run(args = ARGV) = process_args args if .include? :MailQ then mailq exit end if [:Daemon] then require 'webrick/server' @@pid_file = File.([:Pidfile], [:Chdir]) if File.exists? @@pid_file # check to see if process is actually running pid = '' File.open(@@pid_file, 'r') {|f| pid = f.read.chomp } if system("ps -p #{pid} | grep #{pid}") # returns true if process is running, o.w. false $stderr.puts "Warning: The pid file #{@@pid_file} exists and ar_sendmail is running. Shutting down." exit else # not running, so remove existing pid file and continue self.remove_pid_file $stderr.puts "ar_sendmail is not running. Removing existing pid file and starting up..." end end WEBrick::Daemon.start File.open(@@pid_file, 'w') {|f| f.write("#{Process.pid}\n")} end new().run rescue SystemExit raise rescue SignalException exit rescue Exception => e $stderr.puts "Unhandled exception #{e.}(#{e.class}):" $stderr.puts "\t#{e.backtrace.join "\n\t"}" exit 1 end |
.usage(opts, message = nil) ⇒ Object
Prints a usage message to $stderr using opts
and exits
312 313 314 315 316 317 318 319 320 |
# File 'lib/action_mailer/ar_sendmail.rb', line 312 def self.usage(opts, = nil) if then $stderr.puts $stderr.puts end $stderr.puts opts exit 1 end |
Instance Method Details
#cleanup ⇒ Object
Removes emails that have lived in the queue for too long. If max_age is set to 0, no emails will be removed.
349 350 351 352 353 354 355 356 |
# File 'lib/action_mailer/ar_sendmail.rb', line 349 def cleanup return if @max_age == 0 timeout = Time.now - @max_age conditions = ['last_send_attempt > 0 and created_on < ?', timeout] mail = ActionMailer::Base.email_class.destroy_all conditions log "expired #{mail.length} emails from the queue" end |
#deliver(emails) ⇒ Object
Delivers emails
to ActionMailer’s SMTP server and destroys them.
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 |
# File 'lib/action_mailer/ar_sendmail.rb', line 361 def deliver(emails) settings = [ smtp_settings[:domain], (smtp_settings[:user] || smtp_settings[:user_name]), smtp_settings[:password], smtp_settings[:authentication] ] smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port]) if smtp.respond_to?(:enable_starttls_auto) smtp.enable_starttls_auto unless smtp_settings[:tls] == false else settings << smtp_settings[:tls] end smtp.start(*settings) do |session| @failed_auth_count = 0 until emails.empty? do email = emails.shift begin res = session. email.mail, email.from, email.to email.destroy log "sent email %011d from %s to %s: %p" % [email.id, email.from, email.to, res] rescue Net::SMTPFatalError => e log "5xx error sending email %d, removing from queue: %p(%s):\n\t%s" % [email.id, e., e.class, e.backtrace.join("\n\t")] email.destroy session.reset rescue Net::SMTPServerBusy => e log "server too busy, sleeping #{@delay} seconds" sleep delay return rescue Net::SMTPUnknownError, Net::SMTPSyntaxError, TimeoutError => e email.last_send_attempt = Time.now.to_i email.save rescue nil log "error sending email %d: %p(%s):\n\t%s" % [email.id, e., e.class, e.backtrace.join("\n\t")] session.reset end end end rescue Net::SMTPAuthenticationError => e @failed_auth_count += 1 if @failed_auth_count >= MAX_AUTH_FAILURES then log "authentication error, giving up: #{e.}" raise e else log "authentication error, retrying: #{e.}" end sleep delay rescue Net::SMTPServerBusy, SystemCallError, OpenSSL::SSL::SSLError # ignore SMTPServerBusy/EPIPE/ECONNRESET from Net::SMTP.start's ensure end |
#deliver_emails ⇒ Object
469 470 471 472 473 474 475 476 |
# File 'lib/action_mailer/ar_sendmail.rb', line 469 def deliver_emails begin cleanup emails = find_emails deliver(emails) unless emails.empty? rescue ActiveRecord::Transactions::TransactionError end end |
#do_exit ⇒ Object
Prepares ar_sendmail for exiting
419 420 421 422 423 |
# File 'lib/action_mailer/ar_sendmail.rb', line 419 def do_exit log "caught signal, shutting down" self.class.remove_pid_file exit end |
#find_emails ⇒ Object
Returns emails in email_class that haven’t had a delivery attempt in the last 300 seconds.
429 430 431 432 433 434 435 436 |
# File 'lib/action_mailer/ar_sendmail.rb', line 429 def find_emails = { :conditions => ['last_send_attempt < ? and ready', Time.now.to_i - 300] } [:limit] = batch_size unless batch_size.nil? mail = ActionMailer::Base.email_class.find :all, log "found #{mail.length} emails to send" mail end |
#install_signal_handlers ⇒ Object
Installs signal handlers to gracefully exit.
441 442 443 444 |
# File 'lib/action_mailer/ar_sendmail.rb', line 441 def install_signal_handlers trap 'TERM' do do_exit end trap 'INT' do do_exit end end |
#log(message) ⇒ Object
Logs message
if verbose
449 450 451 452 |
# File 'lib/action_mailer/ar_sendmail.rb', line 449 def log() $stderr.puts if @verbose ActionMailer::Base.logger.info "ar_sendmail: #{}" end |
#run ⇒ Object
Scans for emails and delivers them every delay seconds. Only returns if once is true.
458 459 460 461 462 463 464 465 466 467 |
# File 'lib/action_mailer/ar_sendmail.rb', line 458 def run install_signal_handlers loop do now = Time.now deliver_emails break if @once sleep @delay if now + @delay > Time.now end end |
#smtp_settings ⇒ Object
Proxy to ActionMailer::Base::smtp_settings. See api.rubyonrails.org/classes/ActionMailer/Base.html for instructions on how to configure ActionMailer’s SMTP server.
Falls back to ::server_settings if ::smtp_settings doesn’t exist for backwards compatibility.
486 487 488 |
# File 'lib/action_mailer/ar_sendmail.rb', line 486 def smtp_settings @smtp_settings ||= ActionMailer::Base.smtp_settings rescue ActionMailer::Base.server_settings end |