Email to group using EWS C# - c#

I'm using ExchangeWebServices C#.
I'm trying to send an email to distributio list, so
I'm created a group as follow:
private void CreateGroup(ExchangeService service)
{
// Create a new contact group object.
ContactGroup myContactGroup = new ContactGroup(service);
// Give the group a name.
myContactGroup.DisplayName = "TestContactGroup";
// Add some members to the group.
myContactGroup.Members.Add(new GroupMember("Euser#mydomain.com"));
myContactGroup.Members.Add(new GroupMember("Euser1#mydomain.com"));
myContactGroup.Members.Add(new GroupMember("Euser2#mydomain.com"));
// Save the group.
myContactGroup.Save();
}
Now I'm trying to send email to this group, how can i do that?
What i'm tried:
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("TestContactGroup");//Throw an exception "At least one recipient isn't valid."
//email.ToRecipients.Add("TestContactGroup#mydomain.com");//"Return" the mail that "The email address you entered couldn't be found."
email.Subject = "MySubject";
email.Body = new MessageBody("MyBody");
// Send the mail
email.Send();
If I'm trying to send to TestContactGroup i'm got an exception:
"At least one recipient isn't valid."
And if I'm trying to send to TestContactGroup#mydomain.com I'm got an email that the mail isn't found.
So, how can i send an email to group list that I'm crated? Or another way to create distribution list with EWS?
Thanks

Problem solved.
I'm just need to add the group id as follow:
myContactGroup.Id = grpId;
I'm get my group id as follow:
// Instantiate the item view with the number of items to retrieve from the Contacts folder.
ItemView view = new ItemView(9999);
// Request the items in the Contacts folder that have the properties that you selected.
FindItemsResults<Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);
string groupId = string.Empty;
List<ItemId> groupItemIds = new List<ItemId>();
// Loop through all contacts
foreach (Item item in contactItems)
{
//Check to see if ContactGroup
if (item is ContactGroup)
{
//Get the contact group
ContactGroup contactGroup = item as ContactGroup;
groupItemIds.Add(item.Id);//Using to send an email by item id, can classify by DisplayName etc..
}
}

Related

Exchange - routing agent that changes the email massage's recepient from a distribution group type to single email adresses from its members

i'm building a routing agent for exchange 2010 using c# (framework 3.5)
i have a 3rd party app that recieves emails , and authenticate users via their email address.
the problem starts when i sent an email to a distribution group,
the "To" field is set to the D-group email address, and it causes my trouble with the 3rd party app.
how can i convert the TO field of an email massage sent to : xxxGroup#xxx.com
into: user1inGroup#xxx.com;user2inGroup#xxx.com,.....
this is part of my code, i tried deleting the "to" field, but nothing seems to work.
void ownRoutingAgent_OnResolvedMessage(ResolvedMessageEventSource source, QueuedMessageEventArgs messageEventArgs)
{
bool forwardToSeg = false;
if (true) EventViewerLogger.WriteInfo("FromAddress: " + messageEventArgs.MailItem.FromAddress.ToString());
if (true) EventViewerLogger.WriteInfo("SecureSenders: " + m_SecureSenderAddress);
distGroupList = generateDistGroupList();
////////////////////////////////////////////
//Check if recepient is a distrebution group
Random rnd = new Random();
int numOfUser = rnd.Next(0, senderAddresses.Length);
messageEventArgs.MailItem.FromAddress = new RoutingAddress(senderAddresses[numOfUser]);
// run over all recipients list
//foreach (EnvelopeRecipient recp in messageEventArgs.MailItem.Recipients)
//{
foreach (MyClass disGrp in distGroupList)
{
// Checks if Recipients contain an e-mail group.
// if yes, does not route to seg.
if (messageEventArgs.MailItem.Message.To[0].NativeAddress.ToString().ToUpper() == disGrp.emailAdress.ToUpper())
{
messageEventArgs.MailItem.Message.To[0].NativeAddress.Remove(0);
messageEventArgs.MailItem.Message.To.Remove(new EmailRecipient(messageEventArgs.MailItem.Message.To[0].DisplayName.ToString(),messageEventArgs.MailItem.Message.To[0].NativeAddress.ToString()));
foreach (EnvelopeRecipient yywx in messageEventArgs.MailItem.Recipients)
{
//remove group address from mail-recipients
// messageEventArgs.MailItem.Message.To.Add*******
// = messageEventArgs.MailItem.Recipients
//add all group members to the "TO" field
//messageEventArgs.MailItem.Recipients;
}
}
}
use the AddressBook class to do that or expand the recipients of a message in a Transport Agent . if you want to expand a list that would requires an AD call which can be very costly in terms of performance in a Transport Agent.

ServiceObjectPropertyException when trying to get emails with Exchange Webservices?

I am trying to get unread emails and then mark them as read.
I am getting this exception when I run the code:
ServiceObjectPropertyException was unhandeld:
An unhandled exception of type
'Microsoft.Exchange.WebServices.Data.ServiceObjectPropertyException'
occurred in Microsoft.Exchange.WebServices.dll
This error occurred when I try to map my Exchange mail object to my business model object.
This is the Map method:
class MailMapper
{
public static PhishingMail Map(EmailMessage OutlookMail)
{
//Map Exchange email object op Business model email object
PhishingMail readMail = new PhishingMail();
readMail.Subject = OutlookMail.Subject;
return readMail;
}
}
This is the code where it should mark emails as read.
public List<PhishingMail> GetEmails()
{
phishingMailList = new List<PhishingMail>();
FolderId InboxId = new FolderId(WellKnownFolderName.Inbox, "A*******m#i*****nl");
FindItemsResults<Item> findResults = service.FindItems(InboxId, new ItemView(100));
foreach (Item phishingmail in findResults.Items)
{
((EmailMessage)phishingmail).Load(new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.IsRead));
if (!((EmailMessage)phishingmail).IsRead)
{
((EmailMessage)phishingmail).IsRead = true;
((EmailMessage)phishingmail)
.Update(ConflictResolutionMode.AutoResolve);
}
PhishingMail mail = MailMapper.Map((EmailMessage)phishingmail);
phishingMailList.Add(new PhishingMail());
/// Console.WriteLine(mail.Subject);
}
return phishingMailList;
}
What am I doing wrong? What is wrong with map method?
When you load an item, you speficy the properties to load.
item.Load(new PropertySet(PropertySet.FirstClassProperties));
If you need more properties after loading, you can do the following:
Service.LoadPropertiesForItems(items, PropertySet.FirstClassProperties);
I think the issue is that when you Load the email you're only asking for the ID and IsRead properties. Since your map routine fetches the Subject property, you would need to add that to the Load as well.

EWS Managed API: Identify deleted email when fetching from "AllItems" folder

I am using EWS managed API with C# to fetch emails from user accounts. I am fetching the emails from "AllItems" folder and getting different email properties such as subject, datetimesent, etc.
"AllItems" folder also contains emails that are deleted and are in "DeletedItems" folder. I would like to identify whether the email is deleted (i.e. it is in "DeletedItems" folder) and if possible, when the email was deleted.
Below is the code I am using. I could not find a property that would identify whether the email is deleted.
FolderView viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) };
ItemView viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) };
SearchFilter folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "AllItems");
FolderId rootFolderId = new FolderId(WellKnownFolderName.Root);
FindItemsResults<Item> findResults;
FindFoldersResults AllItemsFolder= service.FindFolders(WellKnownFolderName.Root, folderFilter, viewFolders);
if (AllItemsFolder.Count() > 0)//if we have AllItems folder
{
foreach (Folder folder in AllItemsFolder.Folders)
{
ItemView itv = new ItemView(int.MaxValue);
findResults = service.FindItems(folder.Id, itv);
foreach (Item item in findResults)
{
if (item is EmailMessage)
{
MessageBox.Show(item.Subject);
// Show whether the message is in deleted folder and when message was deleted
}
}
}
}
As you state, I don't think there is a property like that for mail items.
I would use the GetFolder operation with the well known folder name "deleteditems" to get the Id of that folder. Then, I would ignore all mail items that has this Id as ParentFolderId.

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);

Get sender email address from attachment

Question
How would I look at the attachment properties using EWS (Exchange 2013, C#) and retrieve the original sender's email address? Not the email address of the current sender, but the sender of the email that is attached to this email.
What I Did
Lots of googling has shown me only how to retrieve the sender of the current email and not the attachement. I do this by
//get sender of email to TR
EmailMessage mes = (EmailMessage)item;
String sender = mes.Sender.Address;
Request
Thoughts? Links? Sample code? I am looking for anything right now that I can use to help me load up the attachment and pull the sender email address. Thanks!
You want to fetch details on attached emails right?
Try This Code Snippet? Assuming _ewsService is a correctly bound service client.
var results = _ewsService.FindItems(WellKnownFolderName.Inbox, new ItemView(100)); //fetch 100 random emails from inbox
foreach (var entry in results.Items)
{
if (entry is EmailMessage)
{
var temp = EmailMessage.Bind(_service, entry.Id);
if (entry.HasAttachments)
{
temp.Load(new PropertySet(EmailMessageSchema.Attachments));
foreach (var singleItem in temp.Attachments)
{
if (singleItem is ItemAttachment)
{
var attachedMail = singleItem as ItemAttachment;
attachedMail.Load();
Console.WriteLine(attachedMail.Item is EmailMessage);
var workingMessage = attachedMail.Item as EmailMessage; //this should give you from, subject, body etc etc.
}
}
}
}
}

Categories