JavaMail 限額管理

JavaMail配額是限定或固定的號碼或郵件的數量在電子郵件存儲。JavaMail API爲每個郵件服務請求調用計數配額。電子郵件服務可以適用下列配額標準:

  • 外發郵件(包括附件)的最大大小。

  • 郵件信息,包括附件的最大大小。

  • 消息的最大大小時,管理員是一個收件人

對於配額管理的JavaMail有以下類別:

Class

描述

public class Quota

This class represents a set of quotas for a given quota root. Each quota root has a set of resources, represented by the Quota.Resource class. Each resource has a name (for example, "STORAGE"), a current usage, and a usage limit. This has only one method setResourceLimit(String name, long limit).

public static class Quota.Resource

Represents an individual resource in a quota root.

public interface QuotaAwareStore

An interface implemented by Stores that support quotas. The getQuota and setQuota methods support the quota model defined by the IMAP QUOTA extension.GmailSSLStore, GmailStore, IMAPSSLStore, IMAPStore are the known implementing classes of this interface.

讓我們來看看和例子在下面的章節會檢查郵件存儲名稱,並限制其使用。

創建Java類

創建一個Java類文件QuotaExample,是其內容如下:

package com.yiibai; import java.util.Properties; import javax.mail.Quota; import javax.mail.Session; import javax.mail.Store; import com.sun.mail.imap.IMAPStore; public class QuotaExample { public static void main(String[] args) { try { Properties properties = new Properties(); properties.put("mail.store.protocol", "imaps"); properties.put("mail.imaps.port", "993"); properties.put("mail.imaps.starttls.enable", "true"); Session emailSession = Session.getDefaultInstance(properties); // emailSession.setDebug(true); // create the IMAP3 store object and connect with the pop server Store store = emailSession.getStore("imaps"); //change the user and password accordingly store.connect("imap.gmail.com", "abc@gmail.com", "*****"); IMAPStore imapStore = (IMAPStore) store; System.out.println("imapStore ---" + imapStore); //get quota Quota[] quotas = imapStore.getQuota("INBOX"); //Iterate through the Quotas for (Quota quota : quotas) { System.out.println(String.format("quotaRoot:'%s'", quota.quotaRoot)); //Iterate through the Quota Resource for (Quota.Resource resource : quota.resources) { System.out.println(String.format( "name:'%s', limit:'%s', usage:'%s'", resource.name, resource.limit, resource.usage)); } } } catch (Exception e) { e.printStackTrace(); } } }

這裏是連接通過IMAP(imap.gmail.com)服務器的Gmail服務,爲IMAPStore實現QuotaAwareStore。一旦你獲得了存儲對象,獲取配額陣列和遍歷並打印相關信息。

編譯並運行

現在,我們的類是準備好了,讓我們編譯上面的類。我已經保存了類QuotaExample.java到目錄 : /home/manisha/JavaMailAPIExercise. 我們需要javax.mail.jar 和 activation.jar在classpath中。執行下面的命令從命令提示符編譯類(兩個jar被放置在/home/manisha/ 目錄下):

javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: QuotaExample.java

現在,這個類被編譯,執行下面的命令來運行:

java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: QuotaExample

驗證輸出

您應該看到類似的消息在命令控制檯上:

imapStore ---imaps://abc%[email protected]
quotaRoot:''
name:'STORAGE', limit:'15728640', usage:'513'