Tính năng tiện ích

Gửi tin với tùy chọn Bình chọn

Microsoft Outlook cho phép người dùng tạo một cuộc thăm dò khi soạn tin mới. Điều này được thực hiện bằng cách bao gồm các tùy chọn bình chọn như Có, Không, Có thể, v.v. Lớp FollowUpOptions được Aspose.Email cung cấp, có thuộc tính VotingButtons cho phép đặt hoặc lấy giá trị các tùy chọn bình chọn. Bài viết này đưa ra ví dụ chi tiết về việc tạo MapiMessage với các tùy chọn bình chọn để tạo một cuộc thăm dò và sau đó gửi tin bằng client Exchange Web Service (EWS).

Tạo và Gửi tin với tùy chọn Bình chọn

Đoạn mã sau cho bạn thấy cách tạo một tin mới và sau đó gửi nó kèm tùy chọn bình chọn.

String address = "firstname.lastname@aspose.com";

IEWSClient client = EWSClient.getEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
MailMessage message = createTestMessage(address);

// Set FollowUpOptions Buttons
FollowUpOptions options = new FollowUpOptions();
options.setVotingButtons("Yes;No;Maybe;Exactly!");

client.send(message, options);

Các phương thức mẫu trong ví dụ

Đoạn mã sau cho bạn thấy cách sử dụng các phương thức được dùng trong ví dụ trên.

private static MailMessage createTestMessage(String address) {
    MailMessage eml = new MailMessage(address, address, "Flagged message",
            "Make it nice and short, but descriptive. The description may appear in search engines' search results pages...");

    return eml;
}

Tạo tin RE và FW từ tệp MSG

IEWSClient cho phép các nhà phát triển tạo tin RE (Reply/Reply All) và FW (Forward) từ một tin nguồn. Tin nguồn được xác định bằng cách chọn một ExchangeMessageInfo từ ExchangeMessageInfoCollection được lấy bởi IEWSClient.listMessages(). Tham số khác là thực tế MailMessage để gửi như tin RE hoặc FW. Đoạn mã sau cho bạn thấy cách tạo một tài khoản mẫu được dùng để gửi tin và sau đó các tính năng Trả lời và Chuyển tiếp tin được minh họa với tin mẫu đó. Để thực hiện nhiệm vụ này:

  1. Khởi tạo đối tượng IEWSClient bằng cách cung cấp thông tin đăng nhập hợp lệ.
  2. Gửi một vài tin nhắn mẫu.
  3. Gọi các hàm IEWSClient.reply(), IEWSClient.replyAll() và IEWSClient.forward() để gửi tin nhắn.
IEWSClient client = EWSClient.getEWSClient(mailboxUri, credential);

try {
    MailMessage message = new MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " + UUID.randomUUID().toString(),
            "TestMailRefw Implement ability to create RE and FW messages from source MSG file");

    client.send(message);

    ExchangeMessageInfoCollection messageInfoCol = client.listMessages(client.getMailboxInfo().getInboxUri());
    if (messageInfoCol.size() == 1)
        System.out.println("1 message in Inbox");
    else
        System.out.println("Error! No message in Inbox");

    MailMessage message1 = new MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " + UUID.randomUUID().toString(),
            "TestMailRefw Implement ability to create RE and FW messages from source MSG file");

    client.send(message1);
    messageInfoCol = client.listMessages(client.getMailboxInfo().getInboxUri());

    if (messageInfoCol.size() == 2)
        System.out.println("2 messages in Inbox");
    else
        System.out.println("Error! No new message in Inbox");

    MailMessage message2 = new MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " + UUID.randomUUID().toString(),
            "TestMailRefw Implement ability to create RE and FW messages from source MSG file");
    message2.getAttachments().addItem(Attachment.createAttachmentFromString("Test attachment 1", "Attachment Name 1"));
    message2.getAttachments().addItem(Attachment.createAttachmentFromString("Test attachment 2", "Attachment Name 2"));

    // Reply, Replay All and forward Message
    client.reply(message2, messageInfoCol.get_Item(0));
    client.replyAll(message2, messageInfoCol.get_Item(0));
    client.forward(message2, messageInfoCol.get_Item(0));
} catch (java.lang.RuntimeException ex) {
    System.out.println("Error in program" + ex.getMessage());
}

Hỗ trợ OAuth cho EWS với Office 365

Aspose.Email API cung cấp hỗ trợ cho Exchange Web Service (EWS) với Office 365. API’s EWSClient giao diện cung cấp phương thức overload cung cấp OAuthNetworkCredential được sử dụng làm đầu vào để truy cập tài khoản Exchange qua OAuth. Người dùng cần cung cấp Authority, Client Id, Client App Uri và các tham số Resource để hoạt động. Đoạn mã sau cho thấy Hỗ trợ OAuth cho EWS với Office 365.

// token provider
/*ITokenProvider provider = new ITokenProvider() {

    @Override
    public void dispose() {
    }

    @Override
    public OAuthToken getAccessToken(boolean ignoreExistingToken) {
        return null;
    }

    @Override
    public OAuthToken getAccessToken() {
        return null;
    }
};

NetworkCredential credentials = new OAuthNetworkCredential(provider);*/

// accessToken
NetworkCredential credentials = new OAuthNetworkCredential("accessToken");

IEWSClient client = EWSClient.getEWSClient("https://outlook.office365.com/ews/exchange.asmx", credentials);
client.listMessages();

Hỗ trợ Ghi log trong Client Exchange

Aspose.Email API cung cấp khả năng cung cấp tiện ích ghi log cho client Exchange Web Service.

Ghi log cho EWS Client

client.setLogFileName("logs/ews");
// OR
EWSClient.setCommonLogFileName("logs/ews");

Thêm Header trong Yêu cầu EWS

Aspose.Email API cho phép thêm header vào các yêu cầu Exchange. Điều này có thể được dùng để thêm header vào các yêu cầu EWS cho các mục đích khác nhau. Một ví dụ là thêm header X-AnchorMailbox được sử dụng để quản lý các vấn đề throttling trên máy chủ Exchange. Phương thức addHeader của IEWSClient được dùng để thêm header vào các yêu cầu EWS như trong đoạn mã sau.

final IEWSClient client = EWSClient.getEWSClient("exchange.domain.com/ews/Exchange.asmx", "username", "password", "");
try {
    client.addHeader("X-AnchorMailbox", "username@domain.com");
    ExchangeMessageInfoCollection messageInfoCol = client.listMessages(client.getMailboxInfo().getInboxUri());
} finally {
    client.dispose();
}

Trả về ID Yêu cầu Client trong Header

Cái return-client-request-id header được gửi trong yêu cầu và được server sử dụng để xác định liệu client-request-id header được client chỉ định nên được trả về trong phản hồi của server. Các phương thức sau được sử dụng trong thao tác này:

try (IEWSClient client = createEWSClient())
{
    // Client will create random id and pass it to the server.
    // The server should include this id in request-id header of all responses.
    client.setReturnClientRequestId(true);
    
    client.setLogFileName("ews.log");
    client.getMailboxInfo();
}

Làm việc với Nhắn tin Thống nhất

Aspose.Email có thể lấy thông tin nhắn thống nhất từ Exchange Server 2010. Nhắn tin thống nhất như lấy thông tin cấu hình, khởi tạo cuộc gọi đi, lấy thông tin cuộc gọi theo ID và ngắt cuộc gọi theo ID hiện đang được hỗ trợ. Đoạn mã mẫu dưới đây cho thấy cách lấy thông tin cấu hình nhắn tin thống nhất từ Microsoft Exchange Server 2010.

IEWSClient client = EWSClient.getEWSClient(mailboxUri, credential);
UnifiedMessagingConfiguration umConf = client.getUMConfiguration();

Nhận Lời khuyên Email

Microsoft Exchange Server đã thêm một số tính năng mới với Exchange Server 2010 và 2013. Một trong số đó cho phép người dùng nhận lời khuyên email khi soạn tin. Những lời khuyên này rất hữu ích vì chúng cung cấp thông tin trước khi email được gửi. Ví dụ, nếu địa chỉ email trong danh sách người nhận sai, một lời khuyên sẽ hiển thị để thông báo rằng địa chỉ email không hợp lệ. Lời khuyên email cũng cho phép bạn xem các phản hồi ngoài giờ làm việc trước khi gửi email: Exchange Server (2010 & 2013) gửi lời khuyên khi email đang được soạn nếu một hoặc nhiều người nhận đã thiết lập phản hồi ngoài giờ. Service Pack 1 cho Microsoft Exchange Server 2010 là yêu cầu cho tất cả các tính năng được trình bày trong bài viết này. Đoạn mã sau cho bạn thấy cách sử dụng EWSClient lớp sử dụng Exchange Web Services, có sẵn trong Microsoft Exchange Server 2007 và các phiên bản sau.

// Create instance of EWSClient class by giving credentials
IEWSClient client = EWSClient.getEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
System.out.println("Connected to Exchange server...");
// Provide mail tips options
MailAddressCollection addrColl = new MailAddressCollection();
addrColl.addMailAddress(new MailAddress("test.exchange@ex2010.local", true));
addrColl.addMailAddress(new MailAddress("invalid.recipient@ex2010.local", true));
GetMailTipsOptions options = new GetMailTipsOptions(MailAddress.to_MailAddress("administrator@ex2010.local"), addrColl, MailTipsType.All);

// Get Mail Tips
MailTips[] tips = client.getMailTips(options);

// Display information about each Mail Tip
for (MailTips tip : tips) {
    // Display Out of office message, if present
    if (tip.getOutOfOffice() != null) {
        System.out.println("Out of office: " + tip.getOutOfOffice().getReplyBody().getMessage());
    }

    // Display the invalid email address in recipient, if present
    if (tip.getInvalidRecipient() == true) {
        System.out.println("The recipient address is invalid: " + tip.getRecipientAddress());
    }
}

Mạo danh Exchange

Mạo danh Exchange cho phép ai đó mạo danh tài khoản khác và thực hiện các nhiệm vụ và thao tác bằng quyền của tài khoản đã mạo danh thay vì quyền của mình. Trong khi ủy quyền cho phép người dùng hành động thay mặt người khác, Mạo danh cho phép họ hành động như người dùng khác. Aspose.Email hỗ trợ Mạo danh Exchange. The EWSClient lớp cung cấp các phương thức ImpersonateUser và ResetImpersonation để hỗ trợ tính năng này.

Để thực hiện nhiệm vụ này:

  1. Khởi tạo ExchangeWebServiceClient cho người dùng 1.
  2. Khởi tạo ExchangeWebServiceClient cho người dùng 2.
  3. Thêm các tin nhắn thử nghiệm vào các tài khoản.
  4. Bật Mạo danh.
  5. Đặt lại Mạo danh.

Đoạn mã sau cho bạn thấy cách sử dụng EWSClient lớp để triển khai tính năng Mạo danh.

// Create instance's of EWSClient class by giving credentials
IEWSClient client1 = EWSClient.getEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser1", "pwd", "domain");
IEWSClient client2 = EWSClient.getEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser2", "pwd", "domain");
{
    String folder = "Drafts";
    try {
        for (ExchangeMessageInfo messageInfo : (Iterable<ExchangeMessageInfo>) client1.listMessages(folder))
            client1.deleteItem(messageInfo.getUniqueUri(), DeletionOptions.getDeletePermanently());
        String subj1 = "NETWORKNET_33354 User User1";
        client1.appendMessage(folder, new MailMessage("User1@exchange.conholdate.local", "To@aspsoe.com", subj1, ""));

        for (ExchangeMessageInfo messageInfo : (Iterable<ExchangeMessageInfo>) client2.listMessages(folder))
            client2.deleteItem(messageInfo.getUniqueUri(), DeletionOptions.getDeletePermanently());
        String subj2 = "NETWORKNET_33354 User User2";
        client2.appendMessage(folder, new MailMessage("User2@exchange.conholdate.local", "To@aspose.com", subj2, ""));

        ExchangeMessageInfoCollection messInfoColl = client1.listMessages(folder);
        // Assert.AreEqual(1, messInfoColl.Count);
        // Assert.AreEqual(subj1, messInfoColl[0].Subject);

        client1.impersonateUser(ItemChoice.PrimarySmtpAddress, "User2@exchange.conholdate.local");
        ExchangeMessageInfoCollection messInfoColl1 = client1.listMessages(folder);
        // Assert.AreEqual(1, messInfoColl1.Count);
        // Assert.AreEqual(subj2, messInfoColl1[0].Subject);

        client1.resetImpersonation();
        ExchangeMessageInfoCollection messInfoColl2 = client1.listMessages(folder);
        // Assert.AreEqual(1, messInfoColl2.Count);
        // Assert.AreEqual(subj1, messInfoColl2[0].Subject);
    } finally {
        try {
            for (ExchangeMessageInfo messageInfo : (Iterable<ExchangeMessageInfo>) client1.listMessages(folder))
                client1.deleteItem(messageInfo.getUniqueUri(), DeletionOptions.getDeletePermanently());
            for (ExchangeMessageInfo messageInfo : (Iterable<ExchangeMessageInfo>) client2.listMessages(folder))
                client2.deleteItem(messageInfo.getUniqueUri(), DeletionOptions.getDeletePermanently());
        } catch (java.lang.RuntimeException e) {
        }
    }
}

Tính năng Tự động Khám phá bằng EWS

Aspose.Email API cho phép bạn khám phá các thiết lập của Exchange Server bằng cách sử dụng EWS Client. 

AutodiscoverService svc = new AutodiscoverService();
svc.setCredentials(new NetworkCredential(email, password));

IGenericDictionary</* UserSettingName */Integer, Object> userSettings = svc.getUserSettings(email, UserSettingName.ExternalEwsUrl).getSettings();
String ewsUrl = (String) userSettings.get_Item(UserSettingName.ExternalEwsUrl);
System.out.println("Auto discovered EWS Url: " + ewsUrl);

Hủy Khôi phục PST tới Exchange Server

Aspose.Email API cho phép bạn khôi phục tệp PST vào Exchange Server. Tuy nhiên, nếu thao tác mất nhiều thời gian do kích thước PST lớn, có thể cần chỉ định tiêu chí để hủy bỏ thao tác. Điều này có thể thực hiện bằng API như trong đoạn mã mẫu dưới đây.

final IEWSClient client = EWSClient.getEWSClient("https://exchange.office365.com/ews/exchange.asmx", "username", "password");
try {
    final long startTime = System.currentTimeMillis();
    final AtomicInteger processedItems = new AtomicInteger(0);
    final long S15 = 15 * 1000;

    BeforeItemCallback callback = new BeforeItemCallback() {
        public void invoke(ItemCallbackArgs item) {
            if (System.currentTimeMillis() - startTime > S15) {
                throw new AbortRestoreException();
            }

            processedItems.incrementAndGet();
        }
    };

    try {
        // create a test pst and add some test messages to it
        PersonalStorage pst = PersonalStorage.create(new ByteArrayOutputStream(), FileFormatVersion.Unicode);
        FolderInfo folder = pst.getRootFolder().addSubFolder("My test folder");
        for (int i = 0; i < 20; i++) {
            MapiMessage message = new MapiMessage("from@gmail.com", "to@gmail.com", "subj", "body");
            folder.addMessage(message);
        }
        RestoreSettings rs = new RestoreSettings();
        rs.setBeforeItemCallback(callback);

        // now restore the PST with callback
        client.restore(pst, rs);
        System.out.println("Success!");
    } catch (AbortRestoreException e) {
        System.out.println("Timeout! " + processedItems.get());
    }
} finally {
    client.dispose();
}