Send Bulk Email and Monitoring using Code

Hi Folks,

Here comes my next and an interesting post. This post will help you out to send bulk emails from your CRM application through .Net code. And wait it is not just about sending emails and you can monitor the status of the operation as well in your application.

  1. Open your Visual Studio and create a new project.
  2. In this example we will create a new Windows Forms Application. You can use any other application as per your convenience.

 

  1. In this example we will not go through the initial connection string to connect to CRM. This post is assuming you know the basic connection to CRM application. Place this code in the form load along with the connection string with CRM.

     

        // Get a system user to use as the sender.

WhoAmIRequest emailSenderRequest = new
WhoAmIRequest();

WhoAmIResponse emailSenderResponse =

_serviceProxy.Execute(emailSenderRequest) as
WhoAmIResponse;

 

// Set trackingId for bulk mail request.

Guid trackingId = Guid.NewGuid();

 

1.
 

SendBulkMailRequest bulkMailRequest = new  
SendBulkMailRequest()  

{

// Create a query expression for the bulk operation to use to retrieve

// the contacts in the email list.

Query = new
QueryExpression()

{

EntityName = Contact.EntityLogicalName,

ColumnSet = new
ColumnSet(new
String[] { "contactid" }),

Criteria = new
FilterExpression()

{

Conditions =

{

new
ConditionExpression("contactid",ConditionOperator.In, _contactsIds)

}

}

},

// Set the Sender.

Sender = new
EntityReference(SystemUser.EntityLogicalName, emailSenderResponse.UserId),

// Set the RegardingId - this field is required.

RegardingId = Guid.Empty,

RegardingType = SystemUser.EntityLogicalName,

// Use a built-in Microsoft Dynamics CRM email template.

// NOTE: The email template's "template type" must match the type of

// customers in the email list. Our list contains contacts, so our

// template must be for contacts.

 

//Here modify the guid with your record.

TemplateId = new
Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),

RequestId = trackingId

};

 

// Execute the async bulk email request

SendBulkMailResponse resp = (SendBulkMailResponse)

_serviceProxy.Execute(bulkMailRequest);

 

  1. Now comes the interesting portion of monitoring the bulk email:

     

 

// Now that we've executed the bulk operation, we need to retrieve it

// using our tracking Id.

 

QueryByAttribute bulkQuery = new
QueryByAttribute()

{

EntityName = AsyncOperation.EntityLogicalName,

ColumnSet = new
ColumnSet(new
string[] { "requestid", "statecode" }),

Attributes = { "requestid" },

Values = { trackingId }

};

 

// Retrieve the bulk email async operation.

EntityCollection aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);

 

// Monitor the async operation via polling.

int secondsTicker = ARBITRARY_MAX_POLLING_TIME;

 

AsyncOperation createdBulkMailOperation = null;

 

while (secondsTicker > 0)

{

// Make sure the async operation was retrieved.

if (aResponse.Entities.Count > 0)

{

// Grab the one bulk operation that has been created.

createdBulkMailOperation = (AsyncOperation)aResponse.Entities[0];

 

// Check the operation's state.

if (createdBulkMailOperation.StateCode.Value !=

AsyncOperationState.Completed)

{

// The operation has not yet completed.

// Wait a second for the status to change.

System.Threading.Thread.Sleep(1000);

secondsTicker--;

 

// Retrieve a fresh version the bulk delete operation.

aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);

}

else

{

// Stop polling because the operation's state is now complete.

secondsTicker = 0;

}

}

else

{

// Wait a second for the async operation to activate.

System.Threading.Thread.Sleep(1000);

secondsTicker--;

 

// Retrieve the entity again

aResponse = _serviceProxy.RetrieveMultiple(bulkQuery);

}

}

 

// When the bulk email operation has completed, all sent emails will

// have a status of "Pending Send" and will be picked up by your email

// router. Alternatively, you can then use BackgroundSendEmail to download

// all the emails created with the SendBulkEmail message.

 

#region Check success

 

// Validate async operation succeeded

if (createdBulkMailOperation.StateCode.Value == AsyncOperationState.Completed)

{

MessageBox.Show("Operation Completed."); }

else

{

MessageBox.Show("Operation not yet Completed."); }

 

#endregion

 

Hope this helps.

 

Happy coding!!