serving the solutions day and night

Pages

Tuesday, May 13, 2014

MS Dynamics CRM - Create Email

List<ActivityParty> ccUsers = CCUsers(string ccEmails);
List<ActivityParty> toUsers = DNSTeamUsers();

CreateEmail(toUsers, ccUsers, subject, body);

//Create Email address, email will be in Draft format.

private Guid CreateEmail(List<ActivityParty> toUsers, List<ActivityParty> ccUsers, string subject, string body)
{
    Guid orgid, userid;
    SystemUserEntity.WhoAmIResponse(out orgid, out userid);

    ActivityParty fromUser = new ActivityParty
    {
    PartyId = new EntityReference(SystemUser.EntityLogicalName, userid)
    };

    Email email = new Email();
    email.From = new ActivityParty[] { fromUser };
  
    if (toUsers!=null)
    email.To = toUsers.ToArray();
  
    if (ccUsers!=null)
    email.Bcc = ccUsers.ToArray();
 
    email.Subject = subject;

    email.Description = body;

    //Assign regarding    
    email.RegardingObjectId = new EntityReference(contact.EntityLogicalName, contactid);
   
    //connect OrganizationServiceProxy
    Guid emailGUID = CRMServiceProxy.Create(email);
    return emailGUID;
}


//To email address from DNS Team users.

private List<ActivityParty> DNSTeamUsers()
{
    List<ActivityParty> toUsers = new List<ActivityParty>();
    using (XrmServiceContext xsContext = new XrmServiceContext(CRMServiceProxy))
    {
    var qry = from sus in xsContext.SystemUserSet
          join bus in xsContext.BusinessUnitSet on sus.BusinessUnitId.Id equals bus.BusinessUnitId.Value
          where bus.Name == TeamEntity.DNSTeamName
          where sus.InternalEMailAddress != null
          select new
          {
            sus.SystemUserId
          };

    foreach (var rec in qry)
    {
        ActivityParty toUser = new ActivityParty();
        toUser.PartyId = new EntityReference(SystemUser.EntityLogicalName, rec.SystemUserId.Value);
        toUsers.Add(toUser);
    }
    }
    return toUsers;
}

//CC email address from global settings or configuration
//ccEmails format - email@yahoo.com;email@gmail.com;email@hotmail.com      

private List<ActivityParty> CCUsers(string ccEmails)
{
    List<ActivityParty> ccUsers = new List<ActivityParty>();

    if (!string.IsNullOrEmpty(ccEmails))
    {
    if (ccEmails.Contains(";"))
    {
        string[] emails = ccEmails.Split(';');

        foreach (string ccEmail in emails)
        {
        if (!string.IsNullOrEmpty(ccEmail))
        {
            ActivityParty ccUser = new ActivityParty();
            ccUser.AddressUsed = ccEmail;
            ccUsers.Add(ccUser);
        }
        }
    }
    else
    {
        ActivityParty ccUser = new ActivityParty();
        ccUser.AddressUsed = ccEmails;
        ccUsers.Add(ccUser);
    }
    }
    return ccUsers;
}

No comments: