Thursday, August 21, 2008

Create and Send Email Activity

You can easily craete and send an email activity in MS CRM 3.0 / 4.0.

If you experience "MS CRM 4.0: Generic SQL error 0x80044150" error, Please enable the impersonation in the web.config:

Here is the simple code to Create and Send Email Activity:

public bool CreateAndSendEmail(Lookup EmailFrom, Lookup EmailTo, string EmailSubject, string EmailDescription, Lookup RegardingObject)
{
    try
    {
        #region Create Email Object
 
            email ObjEmail = new email();
 
            if(EmailFrom != null)
            {
                activityparty ObjFrom = new activityparty();
                ObjFrom.partyid = EmailFrom;
                ObjEmail.from = new activityparty[] { ObjFrom };
            }
 
            activityparty ObjTo = new activityparty();
            ObjTo.partyid = EmailTo;
            ObjEmail.to = new activityparty[] { ObjTo };
 
            // Assign Subject
            ObjEmail.subject = EmailSubject;
 
            // Assign Description
            ObjEmail.description = EmailDescription;
 
            CrmSdk.CrmBoolean direction = new CrmSdk.CrmBoolean();
            direction.Value = true;
            ObjEmail.directioncode = direction;
 
            //Regarding Case
            if(RegardingObject != null)
                ObjEmail.regardingobjectid = RegardingObject;
 
            //Create Email
            try
            {
                Guid EmailGuid = Service.Create(ObjEmail);
 
                // Create a SendEmail request.
                SendEmailRequest emailRequest = new SendEmailRequest();
                emailRequest.EmailId = EmailGuid;
                emailRequest.TrackingToken = "";
                emailRequest.IssueSend = true;
 
                // Send the email message.
                SendEmailResponse emailResponse = (SendEmailResponse)Service.Execute(emailRequest);
 
                return true;
            }
 
            catch (SoapException)
            {
                return false;
            } 
 
        #endregion Create Email Object
    }
    
    catch (SoapException)
    {
        return false;
    }
}


Hope you find this code helpful.
Happy Coding.

1 comment:

Anonymous said...

This really helped me thanks