Utility Features
Sending a Message with Voting Option
Microsoft Outlook allows users to create a poll when composed a new message. This is done by including voting options such as Yes, No, Maybe, etc. The FollowUpOptions class offered by Aspose.Email, provides the VotingButtons property that can be used to set or get the value of the voting options. This article provides a detailed example of creating a MapiMessage with voting options for creating a poll and then sending the message using Exchange Web Service (EWS) client.
Creating and Sending a Message with Voting Options
The following code snippet shows you how to create a new message and then send it with voting options.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
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.VotingButtons = "Yes;No;Maybe;Exactly!"; | |
client.Send(message, options); |
Sample Methods Used in Examples
The following code snippet shows you how to use methods used in above example.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
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; | |
} |
Ignore or Bypass Invalid or Expired SSL Certificate
Aspose.Email can handle SSL certificates on Exchange Server using both the ExchangeClient and EWSClient classes. If the SSL certificate has expired or become invalid, Aspose.Email throws an exception due to invalid SSL certificate. Avoid such SSL certificate errors by ignoring them using the method used in the code below. Register the callback handler in your main() or init() method and add the method below as the member of the class.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
public static void Run() | |
{ | |
// Register callback method for SSL validation event | |
ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidationHandler; | |
} | |
// This event handler is called when SSL certificate is verified | |
private static bool RemoteCertificateValidationHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) | |
{ | |
return true; //Ignore the checks and go ahead | |
} |
Creating RE and FW messages from MSG files
IEWSClient lets developers create RE (Reply/Reply All) and FW (Forward) messages from a source message. The source message is identified by selecting a particular ExchangeMessageInfo from ExchangeMessageInfoCollection obtained by IEWSClient.ListMessages(). The other argument is the actual MailMessage to be sent as RE or FW message. The following code snippet shows you how to create a sample account is used to send a message and then the Reply and Forward message features are demonstrated against that sample message. To perform this task:
- Initialize the IEWSClient object by providing valid credentials.
- Send a few sample messages.
- Call the IEWSClient.Reply(), IEWSClient.ReplyAll() and IEWSClient.Forward() functions to send messages.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
string dataDir = RunExamples.GetDataDir_Exchange(); | |
const string mailboxUri = "https://exchange.domain.com/ews/Exchange.asmx"; | |
const string domain = @""; | |
const string username = @"username"; | |
const string password = @"password"; | |
NetworkCredential credential = new NetworkCredential(username, password, domain); | |
IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credential); | |
try | |
{ | |
MailMessage message = new MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " + Guid.NewGuid().ToString(), | |
"TestMailRefw Implement ability to create RE and FW messages from source MSG file"); | |
client.Send(message); | |
ExchangeMessageInfoCollection messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri); | |
if (messageInfoCol.Count == 1) | |
Console.WriteLine("1 message in Inbox"); | |
else | |
Console.WriteLine("Error! No message in Inbox"); | |
MailMessage message1 = new MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " + Guid.NewGuid().ToString(), | |
"TestMailRefw Implement ability to create RE and FW messages from source MSG file"); | |
client.Send(message1); | |
messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri); | |
if (messageInfoCol.Count == 2) | |
Console.WriteLine("2 messages in Inbox"); | |
else | |
Console.WriteLine("Error! No new message in Inbox"); | |
MailMessage message2 = new MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " + Guid.NewGuid().ToString(), | |
"TestMailRefw Implement ability to create RE and FW messages from source MSG file"); | |
message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 1", "Attachment Name 1")); | |
message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 2", "Attachment Name 2")); | |
// Reply, Replay All and forward Message | |
client.Reply(message2, messageInfoCol[0]); | |
client.ReplyAll(message2, messageInfoCol[0]); | |
client.Forward(message2, messageInfoCol[0]); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine("Error in program"+ex.Message); | |
} |
Support for Email Tracking
Aspose.Email API provides support of email tracking using Message Disposition Notification (MDN). This is achieved by requesting the read receipts and creating the required information. The MailMessage class’s ReadReceiptTo property gets or sets the set read receipt address. The CreateReadReceipt and ReadReceiptRequested methods are used for creating and retrieving the information whether read receipts are requested. The following code snippet shows you how to email track using Aspose.Email API.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Send message with the requested read receipt | |
MailMessage mailMessage = new MailMessage("fromAddress", "toAddress", "test MDN","This is a test message with read receipt requested"); | |
// request the read receipt | |
mailMessage.ReadReceiptTo = "fromAddress"; | |
SendMessage(mailMessage, SendMethod.SMTP); | |
// Add multiple ReadReceiptTo addresses. Send message with the requested read receipt. | |
mailMessage = new MailMessage("fromAddress", "toAddress", "test MDN","This is a test message with read receipt requested"); | |
var addressCollection = new Aspose.Email.Mail.MailAddressCollection(); | |
addressCollection.Add("fromAddress"); | |
addressCollection.Add(anotherAddress); | |
mailMessage.ReadReceiptTo = addressCollection; | |
SendMessage(mailMessage, SendMethod.SMTP); | |
// Send message by Exchange | |
mailMessage = new MailMessage("fromAddress", "toAddress", "test MDN","This is a test message with read receipt requested"); | |
mailMessage.ReadReceiptTo = "fromAddress"; | |
SendMessage(mailMessage, SendMethod.Exchange); | |
// Check the request, create and send read receipt. | |
MailMessage emlMDN = FetchMessage(); | |
if (emlMDN.ReadReceiptTo.Count > 0) | |
{ | |
SendMessage(emlMDN.CreateReadReceipt("toAddress", null), SendMethod.SMTP); | |
} | |
// Create the MapiMessage with requested read receipt | |
MapiMessage mapiMessage = new MapiMessage("fromAddress", "toAddress", "test MDN", "This is a read requested mapiMessage", OutlookMessageFormat.Unicode); | |
mapiMessage.ReadReceiptRequested = true; | |
// Create the MailMessage with requested read receipt and convert it to MapiMessage | |
mailMessage = new MailMessage("fromAddress", "toAddress", "test MDN","This is a test message with read receipt requested"); | |
mailMessage.ReadReceiptTo = "fromAddress"; | |
mapiMessage = MapiMessage.FromMailMessage(mailMessage, MapiConversionOptions.UnicodeFormat); | |
mapiMessage = new MapiMessage("dmitry.samodurov@aspose.com", "dmitry.samodurov@aspose.com", "test MDN", "This is a read requested mapiMessage", OutlookMessageFormat.Unicode); | |
mapiMessage.ReadReceiptRequested = true; | |
var getData = MailMessageInterpretorFactory.Instance.GetIntepretor(mapiMessage.MessageClass); | |
var getMessage = mi.Interpret(mapiMessage); |
Support for Logging in Exchange Clients
Aspose.Email API provides the capability to provide logging facility of Exchange Web Service client. This can be achieved by configuring the App.config file.
Logging for EWS Client
<?xml version="1.0" encoding="utf-8" ?> | |
<configuration> | |
<configSections> | |
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > | |
<section name="Aspose.Email.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> | |
</sectionGroup> | |
</configSections> | |
<applicationSettings> | |
<Aspose.Email.Properties.Settings> | |
<setting name="EWSDiagnosticLog" serializeAs="String"> | |
<value>..\..\..\Log\Aspose.Email.EWS.log</value> | |
</setting> | |
<setting name="EWSDiagnosticLog_UseDate" serializeAs="String"> | |
<value>True</value> | |
</setting> | |
</Aspose.Email.Properties.Settings> | |
</applicationSettings> | |
</configuration> |
Adding Headers in EWS Requests
Aspose.Email API allows adding headers to Exchange requests. This can be used to add headers to the EWS requests for different headers that can be used for different purposes. Once such example could be adding the X-AnchorMailbox header that is used to manage the throttling issues on Exchange server. The AddHeader method of the IEWSClient is used to add headers to the EWS requests as shown in the following code snippet.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
using (IEWSClient client = EWSClient.GetEWSClient("exchange.domain.com/ews/Exchange.asmx", "username", "password", "")) | |
{ | |
client.AddHeader("X-AnchorMailbox", "username@domain.com"); | |
ExchangeMessageInfoCollection messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri); | |
} |
Working with Unified Messaging
Aspose.Email can retrieve unified messaging information from Exchange Server 2010. Unified messaging such as getting configuration information, initiating an outbound call, retrieving phone call information by call ID and disconnecting a phone call by ID is supported at present. The following code sample shows how to retrieve unified messaging configuration information from Microsoft Exchange Server 2010.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credential); | |
UnifiedMessagingConfiguration umConf = client.GetUMConfiguration(); |
Getting Mail Tips
Microsoft Exchange Server added several new features with Exchange Server 2010 and 2013. One of them lets users get mail tips when composing an email message. These tips are very useful as they provide information before the email is sent. For example, if an email address is wrong in the recipient’s list, a tip is displayed to let the you know that the email address is invalid. Mail tips also lets you see out of office replies before sending an email: Exchange Server (2010 & 2013) sends the mail tip when the email is being composed if one or more of the recipients have set out of office replies. Microsoft Exchange Server 2010 Service Pack 1 is required for all the features demonstrated in this article. The following code snippet shows you how to uses the EWSClient class which uses Exchange Web Services, available in Microsoft Exchange Server 2007 and later versions.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Create instance of EWSClient class by giving credentials | |
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain"); | |
Console.WriteLine("Connected to Exchange server..."); | |
// Provide mail tips options | |
MailAddressCollection addrColl = new MailAddressCollection(); | |
addrColl.Add(new MailAddress("test.exchange@ex2010.local", true)); | |
addrColl.Add(new MailAddress("invalid.recipient@ex2010.local", true)); | |
GetMailTipsOptions options = new GetMailTipsOptions("administrator@ex2010.local", addrColl, MailTipsType.All); | |
// Get Mail Tips | |
MailTips[] tips = client.GetMailTips(options); | |
// Display information about each Mail Tip | |
foreach (MailTips tip in tips) | |
{ | |
// Display Out of office message, if present | |
if (tip.OutOfOffice != null) | |
{ | |
Console.WriteLine("Out of office: " + tip.OutOfOffice.ReplyBody.Message); | |
} | |
// Display the invalid email address in recipient, if present | |
if (tip.InvalidRecipient == true) | |
{ | |
Console.WriteLine("The recipient address is invalid: " + tip.RecipientAddress); | |
} | |
} |
Exchange Impersonation
Exchange impersonation allows someone to impersonate another account and perform tasks and operations using the impersonated account’s permissions instead of their own. Where delegation lets users act on behalf of other users, Impersonation allows them to act as other users. Aspose.Email supports Exchange Impersonation. The EWSClient class provides the ImpersonateUser and ResetImpersonation methods to facilitate this feature.
To perform this task:
- Initialize the ExchangeWebServiceClient for user 1.
- Initialize the ExchangeWebServiceClient for user 2.
- Append test messages to the accounts.
- Enable Impersonation.
- Reset Impersonation.
The following code snippet shows you how to use the EWSClient class to implement the Impersonation feature.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// 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 | |
{ | |
foreach (ExchangeMessageInfo messageInfo in client1.ListMessages(folder)) | |
client1.DeleteItem(messageInfo.UniqueUri, DeletionOptions.DeletePermanently); | |
string subj1 = string.Format("NETWORKNET_33354 {0} {1}", "User", "User1"); | |
client1.AppendMessage(folder, new MailMessage("User1@exchange.conholdate.local", "To@aspsoe.com", subj1, "")); | |
foreach (ExchangeMessageInfo messageInfo in client2.ListMessages(folder)) | |
client2.DeleteItem(messageInfo.UniqueUri, DeletionOptions.DeletePermanently); | |
string subj2 = string.Format("NETWORKNET_33354 {0} {1}", "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 | |
{ | |
foreach (ExchangeMessageInfo messageInfo in client1.ListMessages(folder)) | |
client1.DeleteItem(messageInfo.UniqueUri, DeletionOptions.DeletePermanently); | |
foreach (ExchangeMessageInfo messageInfo in client2.ListMessages(folder)) | |
client2.DeleteItem(messageInfo.UniqueUri, DeletionOptions.DeletePermanently); | |
} | |
catch { } | |
} | |
} |
Auto Discover Feature using EWS
Aspose.Email API lets you discover about the Exchange Server settings using the EWS Client.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
string email = "asposeemail.test3@aspose.com"; | |
string password = "Aspose@2017"; | |
AutodiscoverService svc = new AutodiscoverService(); | |
svc.Credentials = new NetworkCredential(email, password); | |
IDictionary<UserSettingName, object> userSettings = svc.GetUserSettings(email, UserSettingName.ExternalEwsUrl).Settings; | |
string ewsUrl = (string)userSettings[UserSettingName.ExternalEwsUrl]; | |
Console.WriteLine("Auto discovered EWS Url: " + ewsUrl); |
Abort PST Restore to Exchange Server Operation
Aspose.Email API lets you restore a PST file to Exchange Server. However, if the operation is taking long due to large size PST file, it may be required to specify criterion for aborting the operation. This can be achieved using the API as shown in the following sample code.
Note: The example needs the following class to be added as well.
public class CustomAbortRestoreException : Exception { }
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
using (IEWSClient client = EWSClient.GetEWSClient("https://exchange.office365.com/ews/exchange.asmx", "username", "password")) | |
{ | |
DateTime startTime = DateTime.Now; | |
TimeSpan maxRestoreTime = TimeSpan.FromSeconds(15); | |
int processedItems = 0; | |
BeforeItemCallback callback = delegate | |
{ | |
if (DateTime.Now >= startTime.Add(maxRestoreTime)) | |
{ | |
throw new CustomAbortRestoreException(); | |
} | |
processedItems++; | |
}; | |
try | |
{ | |
//create a test pst and add some test messages to it | |
var pst = PersonalStorage.Create(new MemoryStream(), FileFormatVersion.Unicode); | |
var folder = pst.RootFolder.AddSubFolder("My test folder"); | |
for (int i = 0; i < 20; i++) | |
{ | |
var message = new MapiMessage("from@gmail.com", "to@gmail.com", "subj", new string('a', 10000)); | |
folder.AddMessage(message); | |
} | |
//now restore the PST with callback | |
client.Restore(pst, new Aspose.Email.Clients.Exchange.WebService.RestoreSettings | |
{ | |
BeforeItemCallback = callback | |
}); | |
Console.WriteLine("Success!"); | |
} | |
catch (CustomAbortRestoreException) | |
{ | |
Console.WriteLine($"Timeout! {processedItems}"); | |
} |