1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/lib/action_mailbox/postfix_relayer.rb

67 lines
1.8 KiB
Ruby
Raw Normal View History

2018-11-25 14:30:05 -05:00
# frozen_string_literal: true
require "net/http"
require "uri"
module ActionMailbox
class PostfixRelayer
class Result < Struct.new(:output)
def success?
!failure?
end
def failure?
2018-12-03 22:09:49 -05:00
output.match?(/\A[45]\.\d{1,3}\.\d{1,3}(\s|\z)/)
2018-11-25 14:30:05 -05:00
end
end
2018-11-25 21:35:27 -05:00
CONTENT_TYPE = "message/rfc822"
USER_AGENT = "Action Mailbox Postfix relayer"
2018-11-25 14:30:05 -05:00
2018-11-25 21:35:27 -05:00
attr_reader :uri, :username, :password
def initialize(url:, username: "actionmailbox", password:)
@uri, @username, @password = URI(url), username, password
2018-11-25 14:30:05 -05:00
end
def relay(source)
case response = post(source)
when Net::HTTPSuccess
Result.new "2.0.0 Successfully relayed message to Postfix ingress"
when Net::HTTPUnauthorized
Result.new "4.7.0 Invalid credentials for Postfix ingress"
else
Result.new "4.0.0 HTTP #{response.code}"
end
rescue IOError, SocketError, SystemCallError => error
Result.new "4.4.2 Network error relaying to Postfix ingress: #{error.message}"
rescue Timeout::Error
Result.new "4.4.2 Timed out relaying to Postfix ingress"
rescue => error
Result.new "4.0.0 Error relaying to Postfix ingress: #{error.message}"
end
private
def post(source)
2018-11-25 21:35:27 -05:00
client.post uri, source,
"Content-Type" => CONTENT_TYPE,
"User-Agent" => USER_AGENT,
2018-11-25 14:30:05 -05:00
"Authorization" => "Basic #{Base64.strict_encode64(username + ":" + password)}"
end
def client
@client ||= Net::HTTP.new(uri.host, uri.port).tap do |connection|
2018-11-25 18:31:36 -05:00
if uri.scheme == "https"
require "openssl"
connection.use_ssl = true
connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
2018-11-25 14:30:05 -05:00
connection.open_timeout = 1
connection.read_timeout = 10
end
end
end
end