How to check if a mailserver uses SSL for IMAP communication (Ruby)

124 views Asked by At

I have a service where I need the user to give me access to his email via IMAP.

I need the user_name, password, address and port from my user.

I also need to know if the IMAP connection uses SSL (enable_ssl can be true or false), and I would prefer not to ask my user. Because he probably don't know.

Is it possible to make a query to the mailserver to see if it uses SSL?

My solution so far has been try out both options. First I try to connect with SSL, and then - if this fails - I try to connect without SSL. But some mailservers strike out when I do this, maybe because the first failed connection is still open for some reason.

Here is my working (but clumsy) implementation.

require 'net/imap'
class ImapMailss
  def self.test_connection(address, port, enable_ssl, user_name, password)
    imap = Net::IMAP.new(address, port, enable_ssl)
    imap.login(user_name, password)
    flags = imap.list("", "*")
  end
end

enable_ssl == nil
# First I try to connect with SSL
begin
  true_test = ImapMailss.test_connection(address, port, true, user_name, password)
  if true_test.class.to_s == "Array" # If the mailserver allows me access I get an array of folders like e.g.: [#<struct Net::IMAP::MailboxList attr=[:Hasnochildren], delim="/", name="Feedback requests">, #<struct Net::IMAP::MailboxList attr=[:Hasnochildren], delim="/", name="INBOX">, #<struct Net::IMAP::MailboxList attr=[:Haschildren, :Noselect], delim="/", name="[Gmail]">, #<struct Net::IMAP::MailboxList attr=[:Hasnochildren, :Sent], delim="/", name="[Gmail]/Sent Mail">]
    enable_ssl   = true
  end
rescue => e
  true_error = e
end

# Then I try to connect without SSL
if enable_ssl == nil
  begin
    false_test = ImapMails.test_connection(address, port, false, user_name, password)
  if false_test.class.to_s == "Array"
    enable_ssl   = false
  end
  rescue => e
    false_error = e
  end
end
0

There are 0 answers