Skip to primary content
Skip to secondary content

Passion Dynamics

Microsoft Power Platform & Azure blog by Rawish Kumar

Passion Dynamics

Main menu

  • Home
  • About Me
  • Contact

Tag Archives: how to send email using code

Send Birthday Email To Customers [ Simplest Code Solution]

Posted on May 8, 2018 by Rawish Kumar Prajapati
4

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:

  • Share on X (Opens in new window) X
  • Share on Facebook (Opens in new window) Facebook
Like Loading...
Posted in CRM Code Helpers, Uncategorized | Tagged Author:Rawish, birthday email crm, CRM, get customers whose birthday is today, how to get customer with birthday as today, how to send birthday email CRM, how to send email using code, Linq query to find customers with birthday today, Microsoft Dynamics CRM, send automatic email to customer on birthday, send birthday email automatically in crm, Send Birthday Email To Customers, Send Birthday Email To Customers programatically, Send Birthday Email To Customers programmatically, Send Birthday Email To Customers using console application, send email to contacts on birthday, send email to customer on birthday, send email to customer on their birthday, today customer birthday | 4 Replies
Follow Passion Dynamics on WordPress.com

I'm not an expert; I'm learning!

Top Posts & Pages

  • How to insert dynamic values from custom entities in an email template - Microsoft Dynamics CRM
  • About Me
  • An unsecured or incorrectly secured fault was received from the other party
  • A bit About "Post" In Dynamics 365 CE
  • Create Auto-Number Attribute In Dynamics CRM 365 Using Organization Service + Simple Console Application
  • Alternate Keys
  • Audit History
  • Business Rules
  • Calculated & Rollup Fields
  • Certifications
  • CRM Code Helpers
  • CRM WebApi/Javascript
  • Data Migration
  • Deployment
  • Dynamics 365 For Marketing
  • Dynamics CRM 365 Online
  • Dynamics Portal
  • Microsoft Dynamics CRM Emails
  • Microsoft Dynamics CRM Reporting
  • Microsoft Dynamics CRM SDK
  • Microsoft Dynamics CRM Services
  • Microsoft Dynamics CRM Solutions
  • Reblogged
  • Uncategorized
  • Unified Service Desk for Dynamics CRM
  • Voice Of Customer
  1. Galusz Marton's avatar
    Galusz Marton on Get User’s Teams Using WebApi JavaScript In Dynamics 365September 11, 2024

    For anyone still struggling to retrieve only the Teams that a specific user belongs to, you can filter the returned…

  2. CRM Web Service - Appstore on When To Use Which Microsoft Dynamics CRM Web ServiceMay 27, 2023

    […] source image:passion4dynamics […]

  3. Jessica's avatar
    Jessica on Search For Privilege Name Using Privilege IdMay 2, 2023

    Awesome! Thanks so much for this post!

  4. Alessandro's avatar
    Alessandro on Get Selected Record Information From Main View Or A Subgrid In Dynamics 365April 19, 2023

    Hi, do you know whether it works on Canvas App modals?

  5. Tamilselvan's avatar
    Tamilselvan on Dynamics 365 For Marketing – Retrieve Contacts From A SegmentDecember 23, 2022

    Ok, Got it... To access this schema information, Marketing app has to be installed. It was explained in the MS…

Create a website or blog at WordPress.com
  • Subscribe Subscribed
    • Passion Dynamics
    • Join 47 other subscribers
    • Already have a WordPress.com account? Log in now.
    • Passion Dynamics
    • Subscribe Subscribed
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
 

Loading Comments...
 

    %d