Getting E-Mail and Attachments in Plug-In using LINQ

When updating an e-mail entity, only updated metadata is available in InputParameters.
Here is some code to get the whole entity and attachments using LINQ:

protected void ExecutePostEMailUpdate(LocalPluginContext localContext)
    if (localContext == null)
		throw new ArgumentNullException("localContext");

	IPluginExecutionContext context = localContext.PluginExecutionContext;
	IOrganizationService service = localContext.OrganizationService;
	ITracingService tracingService = localContext.TracingService;

	OrganizationServiceContext serviceContext = new OrganizationServiceContext(service);

	if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
		Entity targetEntity = (Entity)context.InputParameters["Target"];
		if (targetEntity.LogicalName != "email")

			Email email = targetEntity.ToEntity();

			email = (from mail in serviceContext.CreateQuery()
				where (mail.Id == email.Id)
				select mail).FirstOrDefault();

			var attachmentQuery = (from a in serviceContext.CreateQuery()
				where (a.ObjectId == email.ToEntityReference())
				select a);

			foreach (var attachment in attachmentQuery)
				var fileName = attachment.FileName;
		catch (FaultException e)
			throw new InvalidPluginExecutionException(e.ToString());

Leave a Reply

Your email address will not be published. Required fields are marked *