web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

How can I associate incoming emails to accounts based on domain name?

(0) ShareShare
ReportReport
Posted on by 100

Hello everyone, 

 

I am trying to figure out how is it possible to associate incoming messages that are not contacts, but the domain name is associated with a certain account/company.

 

For example the Account email is blah@company.com , but a new employer by the name abcd@company.com sends an email. I want the ability to associate this new contact(already got a workflow for creating a contact out of unknown emails) with the company' based on the domain.

 

Thanks before hand. 

A.

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Jeremy Winchell Profile Picture
    1,165 on at

    Since you are using a workflow to create the contact from an unresolved sender we will stick with the workflow solution.  

    Step 1:  Even though the e-mail address is stored on the Account, I would create another text field on the Account record called "Domain".  In that field you would store @company.com.   If you don't want to use another text field, that's fine but it may make searching a little quicker.

    Step 2:  Using Visual Studio write a custom CRM Workflow Activity that has:

    - 1 input parameter where you pass the e-mail address of the contact to it

    - 1 output parameter that is of type "EntityReference", this will return the matching Account so that you can use it in your workflow and assign it to the Account

    Step 3:  Build out the workflow step logic

    Basically what you will want to do here is execute a RetrieveMultiple or a Linq query depending on what you are more familiar with that will return the AccountId & Name of matching accounts where the domain of the email address matches the domain stored in the Account.

    If you didn't want to setup a 2nd field like I suggested in step 1 then you would just change your logic to way where Account.emailaddress1 contains "@company.com".

    You may or may not have multiple Accounts with the same domain, if you do, you will have to determine what the best criteria is for determining which Account to choose.

    Step 4:  Build the Workflow Activity and register the .dll file generated using the Plug-In Registration tool.  After it's registered update the properties to include a "Group Name"/"Function Name".  This is what will show up in the CRM workflow designer.  (If you are using CRM 4.0, this will be defined in your code instead).

    Step 5:  In the workflow designer when you add a step, you will see your custom group name & function.  You can add it just like any other step to your workflow.  Once you add the step, click "Set Properties" and then you will see the email address parameter that was setup and you can populate it with the email address from the email and/or contact.

    Step 6:  In the next step after the custom one, either a Create/Update of a Contact you can reference the previous step and it will allow you to set the Account on the Contact to the result of your custom step.

    I know the above is a lot to take in and if you are not a developer or familiar with developing for CRM it may seem a bit daunting.  Feel free to contact me directly and I can help you out in getting started.

    Thanks,

    Jeremy

  • Apostolos Proios Profile Picture
    100 on at

    Thanks for the detailed answer J, the fact that i am not a coder, made creating the plugin code feel like hitting my head against a wall. 

     

    I tried this one:

     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Metadata;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Crm.Sdk;

     

    namespace wod.Crm.IncommingEmail

    {

        public class domPlugin : IPlugin

        {

            public void Execute(IServiceProvider serviceProvider)

            {

                // Obtain the execution context from the service provider.

                Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)

                    serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

     

                IOrganizationServiceFactory wod_serviceFactory = null;

     

                IOrganizationService wod_CrmService = null;

     

                try

                {

                    wod_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(

                             typeof(IOrganizationServiceFactory));

                    wod_CrmService = wod_serviceFactory.CreateOrganizationService(context.UserId);

     

                    if (context.MessageName == "Create" &&

                        context.InputParameters.Contains("Target") &&

                        context.InputParameters["Target"] is Entity

                        )

                    {

                        Entity wod_PluginEntity = (Entity)context.InputParameters["Target"];

     

                        //Checking if plugin is trigger for Email entity

                        if (wod_PluginEntity.LogicalName == "email")

                        {

                            // Checking if email direction is incomming

                            if (wod_PluginEntity.Contains("directioncode"))

                            {

                                // Checking if email is incomming

                                if (((Boolean)wod_PluginEntity["directioncode"]) == false)

                                {

                                    EntityCollection wod_IncommingParty = null;

     

                                    wod_IncommingParty = (EntityCollection)wod_PluginEntity["from"];

     

                                    // Checking if plugin entity From field is activityparty entity object

     

                                    if (wod_IncommingParty != null && wod_IncommingParty[0].LogicalName

                                     == "activityparty")

                                    {

                                        EntityReference wod_PartyReference =

                                        (EntityReference)wod_IncommingParty[0]["partyid"];

     

                                        // Checking if email is sent by CRM Contact

                                        if (wod_PartyReference.LogicalName == "contact")

                                        {

                                            // Retrieve sender Contact record

                                            Entity wod_Contact = wod_CrmService.Retrieve("contact",

                                            wod_PartyReference.Id, new ColumnSet(true));

     

                                            // You can write your code for validation, data manipulation here

                                            string piece;

                                            piece = wod_Contact["email"].ToString();

                                            string[] pieces = piece.Split('@');

                                            if (2 == pieces.Length)

                                            {

                                                Entity wod_Account = wod_CrmService.Retrieve("account",

                                                    wod_PartyReference.Id, new ColumnSet(true));

                                                string domain;

                                                domain = pieces[1];

                                                //EntityReference Contacts_Domain = new EntityReference();

                                                //Contacts_Domain = pieces[1];

                                                context.OutputParameters["EmailDomain"] = pieces[1]; 

                                            }

     

                                           // throw new Exception("email account: " + wod_Account["name"]);

     

                                        }

                                    }

                                }

                            }

                        }

                    }

                }

     

                catch (System.Web.Services.Protocols.SoapException ex)

                {

                    throw new InvalidPluginExecutionException(ex.Detail.InnerText);

                }

                catch (Exception ex)

                {

                    throw new InvalidPluginExecutionException(ex.Message);

                }

            }

        }

        }

     

     

    It is bases on wodEmail plugin. but i am not able to get the value. 

     

    Any help would be appreciated. I am posting his in public cause i think many come across the same issue.

     

    Regards,

     

    A.

  • Jeremy Winchell Profile Picture
    1,165 on at

    That's a pretty good start, but I think we can clean it up a little bit.  Since you have a workflow generating a Contact for unresolved Sender's we can simplify the plugin.   Now you can just register the plug-in below on PreCreate of Contact and it will use the Contact email address to find the matching Account.

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Metadata;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Crm.Sdk;

     

    namespace wod.Crm.IncommingEmail
    {

    public class domPlugin : IPlugin

        {

     

            public void Execute(IServiceProvider serviceProvider)

            {

     

                // Obtain the execution context from the service provider.

     

                Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

                IOrganizationServiceFactory wod_serviceFactory = null;

                IOrganizationService wod_CrmService = null;

     

                wod_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                wod_CrmService = wod_serviceFactory.CreateOrganizationService(context.UserId);

     

                if ((context.MessageName == "Create") && (context.PrimaryEntityName == "contact") && (context.InputParameters.Contains("Target")) && (context.InputParameters["Target"] is Entity))

                {

                    Entity _contact = (Entity)context.InputParameters["Target"];

                    //Make sure there is an email address on the contact and it's not already being tied to an Account

                    if((_contact.Contains("emailaddress1")) && (!_contact.Contains("parentcustomerid")))

                    {

                        string _email = (string)_contact["emailaddress1"];

                        string[] _domain = _email.Split('@');

                        if (_domain.Length == 2)

                        {

                            //Retrieve List of Accounts with matching domain

                            QueryExpression _query = new QueryExpression();

                            _query.NoLock = true;

                            _query.EntityName = "account";

                            _query.Distinct = true;

                            _query.Criteria = new FilterExpression();

                            _query.Criteria.FilterOperator = LogicalOperator.And;

                            _query.Criteria.AddCondition("emailaddress1", ConditionOperator.EndsWith, new object[] { "%" + _domain[1].ToString() });

     

                            EntityCollection _accounts = (EntityCollection)wod_CrmService.RetrieveMultiple(_query);

                            if ((_accounts != null) && (_accounts.Entities.Count > 0))

                            {

                                _contact.Attributes.Add("parentcustomerid", new EntityReference(_accounts.Entities[0].LogicalName, _accounts.Entities[0].Id));

                                context.InputParameters["Target"] = _contact;

                            }

                        }

                    }

                }

            }

     

        }


    }

    Jeremy

  • Apostolos Proios Profile Picture
    100 on at

    Hey jeremy,

    your help is great and your code seems perfect to me.

    But it does not seem to attach parent customer as it is supposed to :/

    i created a dummy account with mail test@gmail.com

    sending email from an GMAIL address does not attach the new created contact with the account :/

    I am using synchronous pre-operation on plugin registration tool , and create contact as triggers for the step

    thanks in advance

  • Anthony A Profile Picture
    230 on at

    I know this thread is old, but i'm trying to accomplish the same thing. i tried this code and the query that looks up 'mydomain.com' does not work. it returns 0 records, can someone help me to correct it?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans