This repository has been archived by the owner on Nov 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.rb
57 lines (47 loc) · 1.47 KB
/
mail.rb
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
require 'mailgun'
require 'midi-smtp-server'
# sync stdout so logging shows up
$stdout.sync = true
# Server class
class MailgunSmtpd < MidiSmtpServer::Smtpd
def start
unless ENV.key?('MG_DOMAIN') && ENV.key?('MG_KEY')
printf "#{Time.now}: You must set the environment variables MG_DOMAIN and MG_KEY. Exiting...\n"
exit(false)
end
@@mg_client = Mailgun::Client.new ENV['MG_KEY']
@@mg_domain = ENV['MG_DOMAIN']
super
end
def on_message_data_event(ctx)
logger.debug("[#{ctx[:envelope][:from]}] for recipient(s): [#{ctx[:envelope][:to]}]...")
data = {
to: ctx[:envelope][:to],
message: ctx[:message][:data]
}
@@mg_client.send_message @@mg_domain, data
end
end
listen_port = ENV['MG_SMTPD_PORT'] || 25
listen_addr = ENV['MG_SMTPD_ADDRESS'] || '0.0.0.0'
listen_simul = ENV['MG_SMTPD_SIMULATENOUS_CONNECTIONS'] || 4
listen_options = ENV['MG_SMTPD_OPTIONS'] || {}
printf "#{Time.now}: Starting MailgunSmtpd on #{listen_addr}:#{listen_port}...\n"
server = MailgunSmtpd.new(listen_port, listen_addr, listen_simul, listen_options)
server.start
server.join
# setup exit code
BEGIN {
at_exit {
# check to shutdown connection
if server
puts "#{Time.now}: Shutting down MailgunSmtpd..."
# gracefully connections down
server.shutdown
# check once if some connection(s) need(s) more time
sleep 2 unless server.connections == 0
# stop all threads and connections
server.stop
end
}
}