Skip to content

Passion Dynamics

Microsoft Power Platform blog by Rawish Kumar

  • Home
  • About Me
  • Contact
Posted on May 8, 2018October 26, 2018

Send Birthday Email To Customers [ Simplest Code Solution]

by Rawish Kumar Prajapati.In CRM Code Helpers, Uncategorized.4 Comments on Send Birthday Email To Customers [ Simplest Code Solution]

This is a very common and simple requirement you will get in CRM wherein you have to find a way to send email to customers whose birthday is today. whilst you can achieve this functionality without any code ( workflows + custom fields/entities) but today i will be providing/showing a sample code on how to do that.

This is a simple console application which you can schedule to run every day at specific time.

Required

  1. LinqKit ( you can download from Nuget Manager & add under references)
  2. Early Bound Class

 

Code

Main Program.cs :

using System;
using System.Linq;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System.Net;
using System.Configuration;
using Microsoft.Xrm.Sdk.Client;
using EarlyBound;
using LinqKit;

namespace BirthdayEmail
{
 class Program
 {
 static void Main(string[] args)
 {
 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
 CrmServiceClient crmConn = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CRM"].ConnectionString);

IOrganizationService crmService = crmConn.OrganizationServiceProxy;

OrganizationServiceContext orgContext = new OrganizationServiceContext(crmService);



//use linqkit to build predicate
var predicate = PredicateBuilder.False<Contact>();
 for (int i = Math.Min(140, DateTime.Today.Year - 1900); i > -1; i--)
 {
 DateTime cleanDateTime = new DateTime(DateTime.Today.AddYears(-i).Year, DateTime.Today.AddYears(-1).Month, DateTime.Today.AddYears(-i).Day);
 predicate = predicate.Or(p => p.BirthDate == cleanDateTime.ToUniversalTime());
 }
 var getBirthdays = (from c in orgContext.CreateQuery<Contact>().AsExpandable().Where(predicate)
 select c).ToList();

foreach (var ent in getBirthdays)
 {
 Guid _contactid = ent.Id;

Helper helper = new Helper();
 helper.CreateRequiredRecords(crmService, _contactid);

}
 }
 }
}

helper

using System;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using EarlyBound;




namespace BirthdayEmail
{
 class Helper
 {
 public void CreateRequiredRecords(IOrganizationService crmService, Guid _contactid)
 {

WhoAmIRequest systemUserRequest = new WhoAmIRequest();
 WhoAmIResponse systemUserResponse = (WhoAmIResponse)crmService.Execute(systemUserRequest);
 var userId = systemUserResponse.UserId;

// Create 'From' activity party for the email

ActivityParty fromParty = new ActivityParty
 {
 PartyId = new EntityReference(SystemUser.EntityLogicalName,userId)
 };

// Create 'To' activity party for the email

ActivityParty toParty = new ActivityParty
 {
 PartyId = new EntityReference(Contact.EntityLogicalName, _contactid)
 };


 //format the description field - optional

StringBuilder description = new StringBuilder();
 description.Append("Dear Customer <br/> <br/>");
 description.Append("Wish you a very happy birthday and great life ahead. <br/> <br/>");
 description.Append("Regards, <br/>");
 description.Append("Rawish");


// Create an e-mail message
 Email email = new Email
 {
 To = new ActivityParty[] { toParty },
 From = new ActivityParty[] { fromParty },
 Subject = "Happy Birthday!",
 Description = description.ToString(),
 DirectionCode = true,
 };

Guid _emailId = crmService.Create(email);
 
 //Send Email

SendEmailRequest sendEmail = new SendEmailRequest
 {
 EmailId = _emailId,
 TrackingToken = "",
 IssueSend = true
 };

SendEmailResponse response = (SendEmailResponse)crmService.Execute(sendEmail);

if (response != null)
 {
 Console.WriteLine("completed!");
 
 }
 }
 }
}

 

App.Config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <configSections>
 <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
 <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
 </configSections>
 <connectionStrings>
 <add name="CRM" connectionString="AuthType=Office365; Username= rawish.kumar@passiond.onmicrosoft.com; Password=password;Url=https://passiond.crm8.dynamics.com" />
 </connectionStrings>
 <startup>
 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
 </startup>
 </configuration>

Notice i am using namescpae “EarlyBound”  – that actually my namespace of my early bound generated class.

if you need help in generating the early bound code – please follow my blog :  https://rawishblog.wordpress.com/2018/05/03/unable-to-generate-early-bound-class-dynamics-crm-online/

birthday

 

Few things :

  1. you can use an email template in the email request https://msdn.microsoft.com/en-us/library/gg334461.aspx
  2. All necessary log can be generated or logged to console.

I hope this helps!

 

Share this:

  • Twitter
  • Facebook

Like this:

Like Loading...

Related

Author:Rawishbirthday email crmCRMget customers whose birthday is todayhow to get customer with birthday as todayhow to send birthday email CRMhow to send email using codeLinq query to find customers with birthday todayMicrosoft Dynamics CRMsend automatic email to customer on birthdaysend birthday email automatically in crmSend Birthday Email To CustomersSend Birthday Email To Customers programaticallySend Birthday Email To Customers programmaticallySend Birthday Email To Customers using console applicationsend email to contacts on birthdaysend email to customer on birthdaysend email to customer on their birthdaytoday customer birthday

4 Comments

  1. Pingback: Send Birthday Email To Customers[ Workflow + JavaScript] – Passion Dynamics
  2. Puneet Joshi says:
    September 5, 2018 at 2:32 pm

    Hello, I see you have blogged 2 approaches for very same business requirement, and you have mentioned here that “whilst you can achieve this functionality without any code ( workflows + custom fields/entities)”, I am very curious to know how and if you have already blogged about it please share the link or if you know there is a blog out there please share that too. Thank You.

    LikeLike

    Reply
    1. Rawish Kumar says:
      September 5, 2018 at 2:41 pm

      Hi Puneer, have a look here https://rawishblog.wordpress.com/2018/05/21/send-birthday-email-to-customers-workflow-javascript/

      LikeLike

      Reply
  3. Rawish Kumar says:
    September 5, 2018 at 2:42 pm

    Puneet*

    LikeLike

    Reply

Leave a Reply Cancel reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. ( Log Out /  Change )

Google photo

You are commenting using your Google account. ( Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. ( Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. ( Log Out /  Change )

Cancel

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Post navigation

Previous Previous post: No import packages were found. Exiting the program…
Next Next post: Singleton Retrieve Query Should Not Return More Than 1 Record [Manged Solution Import Error – OnPremise]

Search

Follow Passion Dynamics on WordPress.com

TOP 100 CRM BLOGS AND WEBSITES

Dynamics 365 Certification Badges

Blogs I Follow

  • All Things Dynamics
  • D365 Demystified
  • Andrew Butenko's Blog
  • Rajeev Pentyala - Microsoft power platform blog
  • Debajit's Power Apps & Dynamics 365 Blog
  • Arun Potti's MS CRM blog

Archives

All Posts Categories

My Community

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 39 other followers

My Twitter

My Tweets
Create a website or blog at WordPress.com
  • Home
  • About Me
  • Contact
All Things Dynamics

Blogs on ways to integrate Microsoft Dynamics 365 with other tools

D365 Demystified

A closer look at Microsoft Dynamics 365.

Andrew Butenko's Blog

All I want to share about Development/Customization for Dataverse

Rajeev Pentyala - Microsoft power platform blog

Sharing my knowledge on Power Platform, Dynamics 365, Azure & .Net Stack

Debajit's Power Apps & Dynamics 365 Blog

All about Power Apps & Dynamics

Arun Potti's MS CRM blog

Microsoft Dynamics CRM

Cancel
%d bloggers like this: