EWS error when retrieving complex property - c#

We have an Exchange Web Services application that is throwing errors when an email is referenced that doesn't have a subject.
Our automated process needs to use the subject of the email, so the code is trying to reference it. However, when the subject is missing for an email in the inbox, instead of throwing an error, I want to change the behaviour.
Here is my code:
//creates an object that will represent the desired mailbox
Mailbox mb = new Mailbox(common.strInboxURL);
//creates a folder object that will point to inbox fold
FolderId fid = new FolderId(WellKnownFolderName.Inbox, mb);
... code removed fro brevity ...
// Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
FindItemsResults<Item> results = service.FindItems(fid, searchFilterCollection, view);
if (results.Count() > 0)
{
do
{
// set the prioperties we need for the entire result set
view.PropertySet = new PropertySet(
BasePropertySet.IdOnly,
ItemSchema.Subject,
ItemSchema.DateTimeReceived,
ItemSchema.DisplayTo, EmailMessageSchema.ToRecipients,
EmailMessageSchema.From, EmailMessageSchema.IsRead,
EmailMessageSchema.HasAttachments, ItemSchema.MimeContent,
EmailMessageSchema.Body, EmailMessageSchema.Sender,
ItemSchema.Body) { RequestedBodyType = BodyType.Text };
// load the properties for the entire batch
service.LoadPropertiesForItems(results, view.PropertySet);
so in that code, the error is being thrown on the complex property get on the line service.LoadPropertiesForItems(results, view.PropertySet); at the end.
So, I know I am going to have to do something like a Try..Catch here, however, I would need to check that the Subject property of the mail item exists before I can reference it to see what it is - some kind of chicken and egg problem.
If there is no subject, I need to mark the email as read, send a warning email off to a team, and then gon onwith the next unread email in the mailbox.
Any suggestions about the best way to approach this would be appreciated.
Thanks

Is the Subject not set or is it blank ?
You should be able to isolate any of these type of Emails with a SearchFitler eg use an Exists Search filter for the Subject property and then negate it so it will return any items where the Subject is not set
SearchFilter sfSearchFilteri = new SearchFilter.Exists(ItemSchema.Subject);
SearchFilter Negatesf = new SearchFilter.Not(sfSearchFilteri);
service.FindItems(WellKnownFolderName.Inbox, Negatesf, new ItemView(1000));
Then just exclude those items from your LoadPropertiesForItems
Cheers
Glen

Related

Attempting to show message box and remove CC/To contents when writing new email

Hello and thank you in advance for any help you might be able to offer!
I am looking to create a C# add-in for Outlook that will take new emails that are being written and remove the contents of the To: and CC: fields if either exceeds a count of 10 recipients, then display a message box if either has exceeded 10. I've got some code already but I haven't worked with C# in about 7 years, so I'm very rusty and I feel like I might have done something wrong here. I'd greatly appreciate any insight on how to accomplish my goal.
The code:
private bool CheckRecipients(Outlook.MailItem mail)
{
bool retValue = false;
Outlook.Recipients recipients = null;
Outlook.Recipient recipientTo = null;
Outlook.Recipient recipientCC = null;
try
{
recipientTo = mail.recipientTo;
recipientCC = mail.recipientCC;
while(recipientTo.Count > 10)
{
recipientTo.Remove(1);
MessageBox.Show("You have added more than 10 recipients in the To: field. Please limit the To: field to 10 recipients.");
}
while(recipientCC.Count > 10)
{
recipientCC.Remove(1);
MessageBox.Show("You have added more than 10 recipients in the CC: field. Please limit the CC: field to 10 recipients.");
}
retValue = "something here";
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
if (recipientCC != null) Marshal.ReleaseComObject(recipientCC);
if (recipientTo != null) Marshal.ReleaseComObject(recipientTo);
if (recipients != null) Marshal.ReleaseComObject(recipients);
}
return retValue;
}
After writing the code above, I ran the code as an add-in. Nothing happened.
There is no recipientTo and recipientCC properties in the Outlook object model:
recipientTo = mail.recipientTo;
recipientCC = mail.recipientCC;
Most probably the Recipients property is meant. It returns a Recipients collection that represents all the recipients for the Outlook item. Use Recipients(index) where index is the name or index number to return a single Recipient object. The name can be a string representing the display name, the alias, or the full SMTP email address of the recipient.
The Type property of a new Recipient object is set to the default for the associated AppointmentItem, JournalItem, MailItem, or TaskItem object and must be reset to indicate another recipient type. In case of MailItem recipient - one of the following OlMailRecipientType constants: olBCC, olCC, olOriginator, or olTo.
So, you can iterate over all recipients in the code where you could check the Type property and count recipients in each category if required.
You may find the article which I wrote for the technical blog helpful, see How To: Fill TO,CC and BCC fields in Outlook programmatically.
Another approach is to use a string based properties like To, Cc or Bcc that returns or sets a semicolon-delimited string list of display names for the recipients of the Outlook item. These properties contain the display names only, not the actual email addresses.
I am not sure if you can even compile your code - MailItem object does not implement recipientTo or recipientCC properties. It only exposes MailItem.Recipients collection. You can build your own To/CC lists by looping through the MailItem.Recipients collection and checking the Recipient.Type property (olTo/olCC/olBCC) for each recipient entry.

How to get the MessageId from all exchange items

Hello I recently got into development around EWS. One of the issue came up to me is that a client ask me to import emails into database and he wants to detect the duplicate based on InternetMessageID this way he doesn't have to import the duplicate emails and my code came up to this point.
private static string GetInternetMessageID(Microsoft.Exchange.WebServices.Data.Item email)
{
EmailMessage emailMsg = email as EmailMessage;
string returnId = string.Empty;
if ((emailMsg != null)) {
try {
emailMsg.Load();
//loads additional info, without calling this ToRecipients (and more) is empty
} catch (ArgumentException ex) {
//retry
email.Load();
}
returnId = emailMsg.InternetMessageId;
} else {
//what to do?
}
return returnId;
}
I can handle regular emails, but for special exchange objects such as contact, Calendar, Posts etc it does not work because it could not cast it to an EmailMessage object.
And I know you can extract the internetMessageId from those objects. Because the client used to have another software that extract this ID for them, maybe the property is not called internetMessageID, I think I probally have to extract it from the internetMessageHeader. However when ever I try to get it from the item object it just throws me an error. How do I get the internet messageID from these "Special" exchange items?
PS i am aware of item.id.UniqueID however that is not what I want as this id changes if I move items from folder to another folder in exchange
Only objects that have been sent via the Transport service will have an InternetMessageId so things like Contacts and Tasks because they aren't messages and have never been routed via the Transport service will never have an Internet MessageId. You probably want to look at using a few properties to do this InternetMessageId can be useful for messages PidTagSearchKey https://msdn.microsoft.com/en-us/library/office/cc815908.aspx is one that can be used (if you good this there are various examples of using this property).
If your going to use it in Code don't use the method your using to load the property on each item this is very inefficient as it will make a separate call for each object. Because these I'd's are under 256 Kb just retrieve then when using FindItems. eg
ExtendedPropertyDefinition PidTagSearchKey = new ExtendedPropertyDefinition(0x300B, MapiPropertyType.Binary);
ExtendedPropertyDefinition PidTagInternetMessageId = new ExtendedPropertyDefinition(0x1035, MapiPropertyType.String);
PropertySet psPropSet = new PropertySet(BasePropertySet.IdOnly);
psPropSet.Add(PidTagSearchKey);
psPropSet.Add(PidTagInternetMessageId);
ItemView ItemVeiwSet = new ItemView(1000);
ItemVeiwSet.PropertySet = psPropSet;
FindItemsResults<Item> fiRess = null;
do
{
fiRess = service.FindItems(WellKnownFolderName.Inbox, ItemVeiwSet);
foreach (Item itItem in fiRess)
{
Object SearchKeyVal = null;
if (itItem.TryGetProperty(PidTagSearchKey, out SearchKeyVal))
{
Console.WriteLine(BitConverter.ToString((Byte[])SearchKeyVal));
}
Object InternetMessageIdVal = null;
if (itItem.TryGetProperty(PidTagInternetMessageId, out InternetMessageIdVal))
{
Console.WriteLine(InternetMessageIdVal);
}
}
ItemVeiwSet.Offset += fiRess.Items.Count;
} while (fiRess.MoreAvailable);
If you need larger properties like the Body using the LoadPropertiesForItems Method https://blogs.msdn.microsoft.com/exchangedev/2010/03/16/loading-properties-for-multiple-items-with-one-call-to-exchange-web-services/

Getting unique emails EWS Managed Web API

I am trying to retrieve the emails from the Exchange server using below code:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("username", "somepassword");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("username", RedirectionUrlValidationCallback);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
ServiceResponseCollection<GetItemResponse> items =
service.BindToItems(findResults.Select(item => item.Id), new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients));
return items.Select(item =>
{
return new MailItem()
{
From = ((Microsoft.Exchange.WebServices.Data.EmailAddress)item.Item[EmailMessageSchema.From]).Address,
Recipients = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)item.Item[EmailMessageSchema.ToRecipients]).Select(recipient => recipient.Address).ToArray(),
Subject = item.Item.Subject,
Body = item.Item.Body.ToString(),
};
}).ToArray();
I need to save the subject and body in my database . But i need unique emails becasue i don't want redundant emails to display on my system.
Means every time i synchronize my system with the exchange server , i will get new emails which i hadn't synchronized yet.
If I understand you right, you save the emails obtained by EWS in a Database.
Later you obtain the emails again and so you get the email you already have plus the new ones?
How about working with timestamps?
Get also the CreationTime (or ReceivedTime) of the MailItem and save it in the database too.
After that search in EWS only for mailitems that have CreationTime (or ReceivedTime) later than the last CreationTime (or ReceivedTime) in your Database.
So you only get the new emails.
A possible solution is to move the emails that you processed to the DeletedItems folder by calling
emailMessage.Delete(DeleteMode.MoveToDeletedItems);
Please note that I didn't have to keep a copy of the processed emails within my inbox, so this was a viable solution for me. If you for some reason have to keep a copy within your inbox folder this will not work for you.

code to subscribe a user to a list in mailchimp

When I execute the below code, the mail id is not added to the list, but the "result" parameter contains the value of Email,EUIdl, LEId. Anyone can give the exact code. The code taken from
https://github.com/danesparza/MailChimp.NET
MailChimpManager mc = new MailChimpManager("5323a23b12022d250c23c48253641dd5-us8");
// Create the email parameter
EmailParameter email = new EmailParameter()
{
Email = "riyas.k13#gmail.com"
};
EmailParameter results = mc.Subscribe("33cacee7d8", email);
With the MCAPI this is the call to subscribe to a list, you might want to check all the options in the subscribeOptions, and determine your required Merge values
MCApi mc = new MCApi(ConfigurationManager.AppSettings["MCAPIKey"], false);
var subscribeOptions = new Opt<List.SubscribeOptions>(new List.SubscribeOptions { SendWelcome = true, UpdateExisting = true });
var merges = new Opt<List.Merges>(new List.Merges { { "FNAME", [Subscriber FirstName here] }, { "LNAME", [Subscriber lastName here] } });
if (mc.ListSubscribe(ConfigurationManager.AppSettings["MCListId"], [Subscriber email ], merges, subscribeOptions))
// The user is subscribed Do Something
I had the same issue where the code seemed to work but no email was added to the list. The code does work by the way.
When a new email address is added to the mail list MailChimp sends out a confirmation email to that address, which you need need to confirm naturally.
If you don't do this the new email address won't be added to the list. If you didn't receive any email at the target address check the spam folder or see if any filters have accidentally caught it without you realising.
Sad to say I spent a good few hours going around in circles because of this.
This depends on maichimp list setting when you created the list. There is something called "ask users to confirm the subscription". By default, if admin checked this option, after importing, the users will receive confirmation emails. New added user names will be added only if they confirmed.
If you don't want to sent confirmation emails but directly added new users. Set "DoubleOptIn" to false.
/*
Set subscribe options
*/
MailChimp.Types.List.SubscribeOptions option = new MailChimp.Types.List.SubscribeOptions();
option.UpdateExisting = true;
option.DoubleOptIn = false;
List<MailChimp.Types.List.Merges> lstMerges = new List<MailChimp.Types.List.Merges>();
/*
Merge new users here.
*/
returnStatus = api.ListBatchSubscribe("your MailChimp List ID", lstMerges, option);

Exchange EWS Managed API - unexpected token in XML

Im trying to write a simple sample program which checks for any new mail on an Exchange 2010 server. As far as I can tell, the code I've got should work fine.
I setup the service as follows:
ExchangeService service = new ExchangeService();
service.Credentials = new WebCredentials("user#domain.co.uk", "password");
service.Url = new Uri("https://address/owa");
Upon executing the following code:
int unreadMail = 0;
// Add a search filter that searches on the body or subject.
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Defense"));
// Create the search filter.
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
// Create a view with a page size of 50.
ItemView view = new ItemView(50);
// Identify the Subject and DateTimeReceived properties to return.
// Indicate that the base property will be the item identifier
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
// Order the search results by the DateTimeReceived in descending order.
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
// Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
view.Traversal = ItemTraversal.Shallow;
// Send the request to search the Inbox and get the results.
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);
// Process each item.
foreach (Item myItem in findResults.Items)
{
if (myItem is EmailMessage)
{
if (myItem.IsNew) unreadMail++;
}
}
I get this error (on the FindItemResults line):
'>' is an unexpected token. The expected token is '"' or '''. Line 1, position 63.
This appears to be an error in the XML the API is actually generating, I've tried a few different lots of code (all along the same lines) and not found anything that works.
Any ideas? At a bit of a loss when it comes directly from the API!
Cheers, Daniel.
Nevermind, fixed it - needed to point my service to:
https://servername/ews/Exchange.asmx
and provide regular domain login details such as "username", "password" in order to connect!

Categories