Saturday, October 29, 2011

Create and Send an E-Mail through MS CRM 4.0


using System;
using System.Globalization;
using System.Collections.Generic;
using System.Text;
using System.Web.Services;
using System.Net;
using System.IO;
using System.Configuration;
using TestCrmEmail.Crm.Sdk;
using TestCrmEmail.crmDisc;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Threading;

namespace TestCrmEmail
{
    class CreateEmail
    {
        static void Main(string[] args)
        {
            CreateAndSendCRMEmail("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Test Subject", "Test Body");
        }

        public static void CreateAndSendCRMEmail(string toGuid, string fromGuid, string emailSubject, string emailBody)
        {

            //Set up CRM service
            CRMHelper objCRMHelper = new CRMHelper();
            CrmService crmservice = objCRMHelper.GetCRMService();

            // Create a FROM activity party for the email.
            activityparty fromParty = new activityparty();
            fromParty.partyid = new Lookup();
            fromParty.partyid.type = EntityName.systemuser.ToString();
            fromParty.partyid.Value = new Guid(fromGuid);

            //Create a TO activity party for email
            activityparty toParty = new activityparty();
            toParty.partyid = new Lookup();
            toParty.partyid.type = EntityName.contact.ToString();
            toParty.partyid.Value = new Guid(toGuid);

            //Create a new email
            email emailInstance = new email();

            //set email parameters
            emailInstance.from = new activityparty[] { fromParty };
            emailInstance.to = new activityparty[] { toParty };
            emailInstance.subject = emailSubject;
            emailInstance.description = emailBody;

            //Create a GUId for the email
            Guid emailId = crmservice.Create(emailInstance);

            //Create a SendEmailRequest
            SendEmailRequest request = new SendEmailRequest();
            request.EmailId = emailId;
            request.IssueSend = true;
            request.TrackingToken = "";

            //Execute request
            crmservice.Execute(request);
        }
    }
}