Cameron Aziz
Cameron Aziz

Reputation: 487

Net::IMAP fails: Connection Closed

When I try to open a connection to my Office 365 service, it fails as so:

2.2.0 :001 >     require 'net/imap'
=> true 
2.2.0 :002 >     port = '993'
=> "993" 
2.2.0 :003 >     imap = Net::IMAP.new('outlook.office365.com', port)

Net::IMAP::Error: connection closed
  from /Users/cameronaziz/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/net/imap.rb:1077:in `initialize'
  from (irb):3:in `new'
  from (irb):3

What else do I need to set?

This is the code in my controller:

require 'net/imap'
port = '993'
imap = Net::IMAP.new('outlook.office365.com', port)
imap.authenticate('LOGIN', '***@***.com', '***')
imap.examine('INBOX')

It fails on the new command (same as the console) before I actually set the username / password.

~~~~~~~

Setting the :ssl => true works. But now I still can not connect, as I get:

controller:

imap = Net::IMAP.new('outlook.office365.com', {:port => '993', :ssl => true } )
imap.authenticate('LOGIN', '***@***.com', '***')

error on view:

Net::IMAP::BadResponseError in EmailsController#connect
 Command Argument Error. 11

And the highlighted line in the view is on the authenticate method line now.

When I run imap.capability:

 ["IMAP4", "IMAP4REV1", "AUTH=PLAIN", "AUTH=XOAUTH2", "SASL-IR", "UIDPLUS", "ID", "UNSELECT", "CHILDREN", "IDLE", "NAMESPACE", "LITERAL+"] 

Upvotes: 4

Views: 2664

Answers (2)

Typpex
Typpex

Reputation: 608

Port 993 is usually the way t connect via SSL IMAP so you need to tell ruby you need to connect via SSL such as:

imap = Net::IMAP.new('outlook.office365.com', 993, ssl: true)

Then you can use login or authenticate to connect to your user's mailbox.

The ruby doc state that if you use authenticate method, you need to make sure the imap server can support "LOGIN" or "CRAM-MD5" but in the list you provided i don't see any of those.

["IMAP4", "IMAP4REV1", "AUTH=PLAIN", "AUTH=XOAUTH2", "SASL-IR", "UIDPLUS", "ID", "UNSELECT", "CHILDREN", "IDLE", "NAMESPACE", "LITERAL+"]

So the only way to login to outlook imap is to use map.login method such as: imap.login(login, password)

Upvotes: 4

yossarian
yossarian

Reputation: 1667

IMAP is probably closing the connection because you aren't authenticating in time (or at all).

You should authenticate with either the Net::IMAP#login or the Net::IMAP#authenticate method.

From the docs:

imap.authenticate('LOGIN', 'username', password)

This should also work:

imap.login('username', 'password')

Keep in mind that LOGIN may not be the authentication method in your case. You may want to call imap.capability first and determine whether to proceed with either LOGIN or CRAM-MD5.

Upvotes: 3

Related Questions