You can use the following two functions to retrieve email attachments and append email attachments:
Note that you first have to create the new email message. Your steps are:
1. Create New Email Message
2. Retrieve Email Attachments
3. Attach Email Attachments from Received Message to Target Message
private EntityCollection RetrieveEmailAttachments(Guid emailid)
{
EntityCollection entities = new EntityCollection();
ColumnSet columns = new ColumnSet("activitymimeattachmentid", "objectid", "objecttypecode", "subject", "filename", "filesize", "attachmentid");
QueryExpression query = new QueryExpression
{
ColumnSet = columns,
EntityName = "activitymimeattachment",
Criteria =
{
Conditions =
{
new ConditionExpression("objectid", ConditionOperator.Equal, emailid)
}
}
};
try
{
entities = service.RetrieveMultiple(query);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
return entities;
}
After you get the attachments collection, add the following code to append the attachments to the email message that you created. This is used linked attachments, so no new attachment records are created.
EntityCollection attachments = RetrieveEmailAttachments(receivedEmailId);
// target email id below is the email id of the newly created email message to be created.
if (attachments.Entities.Count > 0)
{
foreach (Entity attachment in attachments.Entities)
{
string attachmentSubject = attachment.Contains("subject") ? attachment["subject"].ToString() : string.Empty;
string attachmentFilename = attachment.Contains("filename") ? attachment["filename"].ToString() : string.Empty;
Entity linkedAttachment = new Entity("activitymimeattachment");
linkedAttachment.Attributes["objectid"] = new EntityReference("email", targetEmailId);
linkedAttachment.Attributes["objecttypecode"] = "email";
if (!string.IsNullOrEmpty(attachmentSubject))
linkedAttachment.Attributes["subject"] = attachmentSubject;
if (!string.IsNullOrEmpty(attachmentFilename))
linkedAttachment.Attributes["filename"] = attachmentFilename;
linkedAttachment.Attributes["attachmentid"] = new EntityReference("attachment", ((EntityReference)attachment.Attributes["attachmentid"]).Id);
service.Create(linkedAttachment);
}
}