forked from angrobg/mailgun-smtp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.rb
67 lines (57 loc) · 1.69 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
58
59
60
61
62
63
64
65
66
67
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
# named arguments caused some odd behavior, incl. proxy not being used
@@mg_client = Mailgun::Client.new(
ENV['MG_KEY'],
'api.eu.mailgun.net',
'v3',
true,
false,
nil,
ENV['MG_PROXY'] ||= nil
)
@@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 = {
from: ctx[:envelope][:from],
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
}
}