Recycle an IMAP Mail Connection

Mail doesn’t seem to offer access to its “take server on/offline” actions. This script demonstrates a workaround that works for IMAP servers to cause Mail to go offline and then online again. It works by setting a bogus server address to the account and then restoring the good address when the account is ready to come online again.

I needed this functionality because my ISP gets finicky about sending emails from the POP server if I haven’t made a connection the IMAP server in a long time. Since Mail keeps the server connection open infinitely (?) long, I had to constantly go through this “Take account offline” “Take account online” dance to get my outgoing messages to deliver.

Hope this helps somebody!

OS version: OS X

-- SET THE NAME OF YOUR IMAP ACCOUNT HERE
set imapName to "chime imap"

-- Take it offline
set savedAddress to my TakeIMAPAccountOffline(imapName)

-- Take it online again
my TakeIMAPAccountOnline(imapName, savedAddress)

-- Takes an account offline and returns the (necessary) server 
-- address required to take it back online again.
on TakeIMAPAccountOffline(theAccountName)
	tell application "Mail"
		-- Get the server
		set theAccount to first imap account whose name is theAccountName
		set theAddress to server name of theAccount
		
		-- Force the account to go offline by setting a bogus server
		set server name of theAccount to "xxx"		
	end tell
	
	-- return the good server address
	return theAddress
end TakeIMAPAccountOffline

-- Takes an account online by checking for new mail
on TakeIMAPAccountOnline(theAccountName, theServerAddress)
	tell application "Mail"
		set theAccount to first imap account whose name is theAccountName
		set server name of theAccount to theServerAddress
		check for new mail for theAccount
	end tell
end TakeIMAPAccountOnline