Skip to content

Instantly share code, notes, and snippets.

@kidpollo
Last active February 1, 2017 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kidpollo/70b6d8f0c91fd98c570a72c99c38e387 to your computer and use it in GitHub Desktop.
Save kidpollo/70b6d8f0c91fd98c570a72c99c38e387 to your computer and use it in GitHub Desktop.
send email fastly
require 'mail'
require 'thread'
require 'parallel'
require 'benchmark'
Mail.defaults do
delivery_method :smtp, options
end
POOL_SIZE = 300
# multi treaded (ish) version is the fastest of all the versions
def send_test_emails_tp(mailbox_accounts, email_body, n=1)
jobs = Queue.new
mailbox_accounts.each do |mailbox|
puts " Queueing emails from #{mailbox}"
n.times{|i| jobs.push({i: (i+1), mailbox: mailbox})}
end
workers = (POOL_SIZE).times.map do
Thread.new do
begin
while args = jobs.pop(true)
Mail.deliver do
to args[:mailbox]
from "desk@stresstestmatic.com"
subject "Postman Stress test email #{args[:i]} of #{n} from #{args[:mailbox]}"
body ("Stress Test email #{args[:i]} Body from #{args[:mailbox]} \n" + email_body)
end
print '.'
end
rescue ThreadError
end
end
end
workers.map(&:join)
puts ' Done'
end
# send n emails to mailbox accounts with email_body
def send_test_emails(mailbox_accounts, email_body, n=1)
mailbox_accounts.each do |mailbox|
puts " Sending Test emails for Mailbox: #{mailbox}"
(1..n).each do |i|
Mail.deliver do
to mailbox
from "desk@stresstestmatic.com"
subject "Postman Stress test email #{i} from #{mailbox}"
body ("Stress Test email #{i} Body from #{mailbox} \n" + email_body)
end
print '.'
end
end
puts ' Done'
end
PROCESS_COUNT = 2
# multi process
def send_test_emails_mp(mailbox_accounts, email_body, n=1)
mb = mailbox_accounts.map do |mailbox|
puts " Queueing emails from #{mailbox}"
(0..(n-1)).map{|i| {i: (i+1), mailbox: mailbox}}
end.flatten
Parallel.each(mb, in_processes: PROCESS_COUNT) {|args|
Mail.deliver do
to args[:mailbox]
from "user@stresstestmatic.com"
subject "Stress test email #{args[:i]} of #{n} from #{args[:mailbox]}"
body ("Stress Test email #{args[:i]} Body from #{args[:mailbox]} \n" + email_body)
end
print '.'
}
end
# multi process thread-pool
def send_test_emails_mp_tp(mailbox_accounts, email_body, n=1)
Parallel.each(mailbox_accounts.each_slice((mailbox_accounts.count/PROCESS_COUNT)).to_a, in_processes: PROCESS_COUNT) {|batch|
send_test_emails_tp(batch, email_body, n)
}
end
# Benchmark.measure { send_test_emails_tp(mailbox_accounts, email_body, 101) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment