Dynamics 365利用email实体的DeliverIncomingEmail来做抓取邮件的进一步处理

我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面的微软最有价值专家(Microsoft MVP),欢迎关注我的微信公众号 MSFTDynamics365erLuoYong ,回复421或者20200726可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!

关于这个消息的官方文档请参考 DeliverIncomingEmail Action 。

为了方便测试,我建立一个public queue,如下:

 

 为Queue的mailbox执行Approve Email 和 Test & Enable Mailbox 后确保其Incoming Email Status 和 Outgoing Email Status 都是Success 。

 

 然后我撰写了一个插件,代码如下,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;

namespace DemoPlugins
{
    public class EmailDeliverIncomingPostPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            tracingService.Trace($"Enter {this.GetType()} on {DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss:ms")}");
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            tracingService.Trace($"context.UserId = {context.UserId}");
            tracingService.Trace($"context.InitiatingUserId = {context.InitiatingUserId}");
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService orgSvc = serviceFactory.CreateOrganizationService(null);
            tracingService.Trace($"DeliverIncomingEmail is a bound action regarding Entity Logical Name = { context.PrimaryEntityName},Entity Id = { context.PrimaryEntityId }");
            var currentEmail = orgSvc.Retrieve("email", context.PrimaryEntityId, new ColumnSet("regardingobjectid"));
            if (currentEmail.Contains("regardingobjectid") && currentEmail.GetAttributeValue<EntityReference>("regardingobjectid").LogicalName == "ly_order")
            {
                tracingService.Trace($"Current email is regarding {currentEmail.GetAttributeValue<EntityReference>("regardingobjectid").LogicalName} with id = {currentEmail.GetAttributeValue<EntityReference>("regardingobjectid").Id}");
                Entity fromEntity = new Entity("activityparty");
                fromEntity["partyid"] = new EntityReference("queue", Guid.Parse("86476289-1fcf-ea11-a813-000d3aa088a2"));
                Entity toEntity = new Entity("activityparty");
                toEntity["addressused"] = "273609697@qq.com";
                Entity emailEntity = new Entity("email");
                emailEntity["from"] = new Entity[] { fromEntity };
                emailEntity["to"] = new Entity[] { toEntity };
                emailEntity["regardingobjectid"] = currentEmail.GetAttributeValue<EntityReference>("regardingobjectid");
                emailEntity["subject"] = "罗勇撰写的通过Dynamics 365自动抓取邮件附件发送新邮件";
                emailEntity["description"] = "<h1>罗勇通过程序创建的邮件</h1>";
                var emailId = orgSvc.Create(emailEntity);
                tracingService.Trace($"Created email with id ={emailId}");
                //如果包括附件,为刚才的邮件添加附件
                if (context.InputParameters.Contains("Attachments") && context.InputParameters["Attachments"] is EntityCollection)
                {
                    var attachmentEC = context.InputParameters["Attachments"] as EntityCollection;
                    if (attachmentEC.Entities.Count >= 1)
                    {
                        tracingService.Trace($"Current email has {attachmentEC.Entities.Count} attachments.");
                        foreach (var attachEntity in attachmentEC.Entities)
                        {
                            var activityMimeAttachment = new Entity("activitymimeattachment");
                            activityMimeAttachment["objectid"] = new EntityReference("email", emailId);
                            activityMimeAttachment["objecttypecode"] = "email";
                            activityMimeAttachment["filename"] = attachEntity.GetAttributeValue<string>("filename");
                            activityMimeAttachment["body"] = attachEntity.GetAttributeValue<string>("body");
                            activityMimeAttachment["mimetype"] = attachEntity.GetAttributeValue<string>("mimetype");
                            orgSvc.Create(activityMimeAttachment);
                            tracingService.Trace($"Created an activitymimeattachment for email with id = {emailId}");
                        }
                    }
                }
                //别忘了发送邮件
                SendEmailRequest sendEmailRequest = new SendEmailRequest
                {
                    EmailId = emailId,
                    IssueSend = true
                };
                orgSvc.Execute(sendEmailRequest);
            }
        }
    }
}

 

我将其注册到email实体的DeliverIncoming 消息的PostOperation阶段,为了减少影响,我将Execution Mode设置为Asynchronous .

 

看我收到了自动转发过来的邮件:

 

 你可能会问,还能获取其他信息,当然还包括其他信息,比如收件人,邮件标题,邮件内容,发件人,收到邮件的时间等,可以通过官方文档看到包括那些,代码可以通过这样来看下:

            foreach(var item in context.InputParameters)
            {
                if (item.Value != null)
                {
                    tracingService.Trace($"InputParameters key = {item.Key} value = {item.Value.ToString()} type = { item.Value.GetType()}");
                }
                else
                {
                    tracingService.Trace($"InputParameters key = {item.Key} value = null");
                }
            }

 

2020年9月13日的官方文档包括其他信息如下:

Parameters

Parameters allow for data to be passed to the action.

PARAMETERS
NameTypeNullableUnicodeDescription
MessageId
Edm.String False False The ID of the email message stored in the email header.
Subject
Edm.String True False The subject line for the email message.
From
Edm.String False False The from address for the email message.
To
Edm.String False False The addresses of the recipients of the email message.
Cc
Edm.String False False The addresses of the carbon copy (Cc) recipients for the email message.
Bcc
Edm.String False False Addresses of the blind carbon copy (Bcc) recipients for the email message.
ReceivedOn
Edm.DateTimeOffset False True The time the message was received on.
SubmittedBy
Edm.String False False The email address of the account that is creating the email activity instance.
Importance
Edm.String False False The level of importance for the email message.
Body
Edm.String False False The message body for the email.
Attachments
activitymimeattachment False True Collection of activity mime attachment (email attachment) instances to attach to the email message.
ExtraProperties
crmbaseentity True True For internal use only.
ValidateBeforeCreate
Edm.Boolean True True Indicates whether to validate before the create operation occurs.

 

我这里提供一个参数值示例,可以看到From的值不只是邮箱,具体情况具体查看。

InputParameters key = MessageId value = <FR1P152MB07091928254D8482F3F57DEE88750@FR1P152MB0709.LAMP152.PROD.OUTLOOK.COM> type = System.String
InputParameters key = From value = "罗 勇" luo.yong@hotmail.com type = System.String
InputParameters key = To value = LuoYongMailforQueue@CRM435740.onmicrosoft.com type = System.String
InputParameters key = Cc value = type = System.String
InputParameters key = Bcc value = type = System.String
InputParameters key = ReceivedOn value = 7/26/2020 11:16:14 AM type = System.DateTime
InputParameters key = SubmittedBy value = "罗 勇" luo.yong@hotmail.com type = System.String
InputParameters key = Importance value = 1 type = System.String
InputParameters key = Body value = body type = System.String
InputParameters key = Attachments value = Microsoft.Xrm.Sdk.EntityCollection type = Microsoft.Xrm.Sdk.EntityCollection
InputParameters key = Subject value = 回复: LuoYong Test Queue给你发一封邮件 CRM:0001001 type = System.String
InputParameters key = ValidateBeforeCreate value = True type = System.Boolean
InputParameters key = ExtraProperties value = Microsoft.Xrm.Sdk.Entity type = Microsoft.Xrm.Sdk.Entity

 

posted @ 2020-07-26 19:37  微软MVP(15-18)罗勇  阅读(473)  评论(0编辑  收藏  举报