文件夹未使用SocketChannels

时间:2018-03-26 14:11:50

标签: java kotlin javamail

我有以下代码:

typealias MessagePredicate = (Message) -> Boolean
object EmailHelper {
    private val session: Session by lazy {
        val props = System.getProperties()
        props["mail.imaps.usesocketchannels"] = "true"
        props["mail.imap.usesocketchannels"] = "true"
        Session.getInstance(props, null)
    }
    private val store = session.getStore("gimap") as GmailStore
    private val idleManager = IdleManager(session, Executors.newSingleThreadExecutor())
    private val folder: GmailFolder by lazy { store.getFolder("INBOX") as GmailFolder }


    init {
        store.connect("imap.gmail.com", "***@gmail.com", "***")
        folder.open(Folder.READ_ONLY)
        idleManager.watch(folder)
    }

    fun watchForMessage(condition: MessagePredicate): CompletableFuture<Message> {
        val promise = CompletableFuture<Message>()
        folder.addMessageCountListener(object : MessageCountAdapter() {
            override fun messagesAdded(e: MessageCountEvent) {
                super.messagesAdded(e)
                e.messages.firstOrNull(condition)?.let {
                    folder.removeMessageCountListener(this)
                    promise.complete(it)
                }
            }
        })
        return promise
    }

}

然而,当我运行此代码时,我遇到以下异常:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.muliyul.MainKt.main(Main.kt:28)
Caused by: javax.mail.MessagingException: Folder is not using SocketChannels
    at com.sun.mail.imap.IdleManager.watch(IdleManager.java:205)
    at com.muliyul.EmailHelper.<clinit>(EmailHelper.kt:40)
    ... 1 more

我事先设置了“mail.imaps.usesocketchannels”属性,我也读过this个问题但我无法解决我的代码出错的问题。

有人能指出我正确的方向吗?

附注:电子邮件提供商是Gmail(显然)。

1 个答案:

答案 0 :(得分:-1)

我发布这个问题一小时后(和3个小时的研究)我终于找到了答案。

您必须将属性"true"设置为mail.imap.usesocketchannels(而不是mail.imaps.usesocketchannelsgimap

这是因为imap是与RewriteEngine on Options -MultiViews RewriteRule ^(item|categories)/([0-9]+)/([a-z\-A-Z]+)/?$ $1.php?id=$2&title=$3 [L] 不同的协议。

耗时3小时。