Sample code to send an email with custom attachement, connected to an Incident entity:
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Configuration;
using System.IO;
using Xrm;
namespace CrmDevelopersHowTo
{
public static class SendEmailSamples
{
public static void SendEmailWithAttachment()
{
// Initiate CRM-connection
var conn = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString);
var service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
Guid regardingObjectGuid = new Guid("----- Incident Id -----"); //Example - could be a lot of other entity types
EntityReference regardingObjectRef = new EntityReference("incident", regardingObjectGuid);
Guid senderGuid = new Guid("----- System User Id -----");
EntityReference senderRef = new EntityReference("systemuser", senderGuid);
ActivityParty fromParty = new ActivityParty()
{
PartyId = senderRef
};
Guid recipientGuid = new Guid("----- Contact Id -----");
EntityReference recipientRef = new EntityReference("contact", recipientGuid);
ActivityParty toParty = new ActivityParty()
{
PartyId = recipientRef
};
Email email = new Email()
{
From = new ActivityParty[] { fromParty },
To = new ActivityParty[] { toParty },
Subject = "Email test",
Description = "<div>This is an email test!</div>",
RegardingObjectId = regardingObjectRef,
DirectionCode = true //Sets the direction to "Outgoing"
};
Guid emailId = service.Create(email);
//Add a custom attachment from the server
FileInfo file = new FileInfo(@"C:\Temp\Logo.png");
if (file.Exists)
{
byte[] bytes = File.ReadAllBytes(file.FullName);
string fileContent = Convert.ToBase64String(bytes);
ActivityMimeAttachment attachment = new ActivityMimeAttachment()
{
ObjectId = new EntityReference("email", emailId),
ObjectTypeCode = "email",
FileName = file.Name,
MimeType = "image/png",
Body = fileContent
};
service.Create(attachment);
}
SendEmailRequest req = new SendEmailRequest()
{
EmailId = emailId,
TrackingToken = "",
IssueSend = true
};
//Send the email
SendEmailResponse res = (SendEmailResponse)service.Execute(req);
}
}
}
Once the email has been sent, it should be visible as an email activity in the selected incident entity’s timeline.
Observe: The sample supplied requires early bound entity classes for ActivityParty, Email, ActivityMimeAttachment, SendEmailRequest and SendEmailResponse!