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)

Crm plugins

(0) ShareShare
ReportReport
Posted on by

I need someone to please help me be able to send emails out from CRM using C# Plugin.There's so many bits and pieces out on the internet and I'm having trouble piecing it all together.

I was able to register the plugin and it's executing on the server, but having a hard time figuring out how to implement this part into the plugin. 

 


Here's the rest of the code. I didn't correctly call the CreateMail( ) function, puzzled how to add the IOrg service and Contact Guid.

 public class SendEmail
    {
       #region Class Level Members
        // Define the IDs needed for this sample.
        private Guid _emailId;
        private Guid _contactId;
        private Guid _userId;
        private OrganizationServiceProxy _serviceProxy;

        #endregion Class Level Members

        #region How To Sample Code
        /// <summary>
        /// Send an e-mail message.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                   CreateMail();


                    // Use the SendEmail message to send an e-mail message.
                    SendEmailRequest sendEmailreq = new SendEmailRequest
                    {
                        EmailId = _emailId,
                        TrackingToken = "",
                        IssueSend = true
                    };

                    SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);
                    Console.WriteLine("Sent the e-mail message.");              
                     
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Community Member Profile Picture
    on at

    You need to call a SendEmailRequest after you created the email record:

    SendEmailRequest sendEmailreq = new SendEmailRequest {

    EmailId = _emailId,

    TrackingToken = "",

    IssueSend = true

    };

    SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);

    msdn.microsoft.com/.../hh210217.aspx

    makdns.blogspot.com/.../ms-dynamics-crm-generate-email.html

    makdns.blogspot.com/.../ms-dynamics-crm-create-email.html

    ashwaniashwin.wordpress.com/.../crm-2011-plugin-to-create-and-send-email-on-opportunity-update

    Please mark the answer as verified if it was helpful.

  • Community Member Profile Picture
    on at

    I'm trying to send an email from CRM and I was able to create the email in Draft mode but it wouldn't send. So I realized that to send, it needs the _serviceProxy passed in.

    Can someone tell me why I am getting this error whenever the code hits the _serviceProxy = new OrganizationServiceProxy(orgURI, null, clientCredentials, null); ???



    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
    Detail: <OrganizationServiceFault xmlns="schemas.microsoft.com/.../Contracts" xmlns:i="www.w3.org/.../XMLSchema-instance">
      <ErrorCode>-2147220970</ErrorCode>
      <ErrorDetails xmlns:a="schemas.datacontract.org/.../System.Collections.Generic">
        <KeyValuePairOfstringanyType>
          <a:key>CallStack</a:key>
          <a:value i:type="b:string" xmlns:b="www.w3.org/.../XMLSchema">  Plugins.Execute(IServiceProvider serviceProvider)
       at PluginProfiler.Library.PluginAppDomainProxy.ExecuteCore(Stopwatch watch, ProfilerExecutionReport report, Object instance, Object executionParameter)
       at PluginProfiler.Library.AppDomainProxy.Execute(ProfilerExecutionConfiguration configuration, ProfilerExecutionReport report)</a:value>
        </KeyValuePairOfstringanyType>
      </ErrorDetails>
      <Message>Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.</Message>
      <Timestamp>2016-03-24T15:17:53.4917178Z</Timestamp>
      <InnerFault i:nil="true" />
      <TraceText i:nil="true" />
    </OrganizationServiceFault>

         IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                            IOrganizationService _crmservice = serviceFactory.CreateOrganizationService(context.UserId);
    
      Uri orgURI = new Uri("testdevelopment.api.crm.dynamics.com/.../Organization.svc");
                                ClientCredentials clientCredentials = new ClientCredentials();
                                clientCredentials.UserName.UserName = "daward@testdevelopment-inc.com";
                                clientCredentials.UserName.Password = "test123!!abc";
                                   OrganizationServiceProxy _serviceProxy;
    
                              /*  using(_serviceProxy = new OrganizationServiceProxy(orgURI, null, clientCredentials, null))
                                {
                                   crmemail.SendEmail(_crmservice, contactguid, userguid, _serviceProxy);
                                }*/
    
                                _serviceProxy = new OrganizationServiceProxy(orgURI, null, clientCredentials, null);
                                crmemail.SendEmail(_crmservice, contactguid, userguid, _serviceProxy);


  • Suggested answer
    nghieppham Profile Picture
    4,755 on at

    Hi Tekwise,

    Please check your Microsoft.Xrm.Sdk, you used the higher sdk version for you plug-in, I think that you are develop in CRM 2013 but you are using sdk of crm 2015 version, just remove this library and use right version.

    You also see this error if you are using external library without using ILMerge or register in GAC.

  • Community Member Profile Picture
    on at

    It needs to be 2015 CRM Online

  • Suggested answer
    nghieppham Profile Picture
    4,755 on at

    Hi Tekwise,

    If you are using CRM online, please check about the registration mode, it must be isolation mode in CRM Online, and if you are using external dll, it should be merge with sdk by the ILMerge.

    Regards,

    Nghiep Pham

  • Community Member Profile Picture
    on at

    The registration mode is Sandbox - the other option is NONE but I cannot select it.

    No external dlls


    Is it the step that is wrong? It's used for Post Operation

  • Suggested answer
    nghieppham Profile Picture
    4,755 on at

    Hi tekwise,

    When you register the plug-in, use use the registration tool in sdk folder to regiester the plug-in, you can follow these links msdn.microsoft.com/.../gg309580.aspx or www.youtube.com/watch

    To merge dll with ILMerge, first to have to install ILMerge to your solution by Nuget, just go to VS->tool->Nuget management and look for ILMerge and install to your solution, note that Copy to local properties of all Microsoft sdk must be set to be false. please follow this link nicknow.net/dynamics-crm-ilmerge-dll-plugin

  • Community Member Profile Picture
    on at

    Yes that is all correct, it has nothing to do with why my code is failing with credential issues

  • Suggested answer
    nghieppham Profile Picture
    4,755 on at

    Hi Tekwise,

    Could you send me the completed code? I read your code, i did not see the line code that you init the context of the plug-in like this line code below:

    in plugin, you no need to init the OrganizationProxy again, you just use like that below code 

    IPluginExecutionContext context = (IPluginExecutionContext)              serviceProvider.GetService(typeof(IPluginExecutionContext));

     IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
     IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    

    in case, you already init the context but still get the error, you have to debug the plugin to see the detail of error, or you can enable the plugin log to trace the bug. This link is the sample to create the basic plugin msdn.microsoft.com/.../gg594416.aspx.

    Please marked if the answer is right.

  • Community Member Profile Picture
    on at

    Hi Pham, I think you're missing the point of why I'm trying to grab the Proxy and not service. I am using it to send the email and one of the argument is sending the org proxy.

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