Attaching a file programmatically to an email - Dynamic CRM

Back to Blog Listing

Within CRM there is the option to add attachments to emails. It is also possible to add these via code using the CRM API, below is instruction on how to do this:

First you must create the email:

Dim em As New Email
Dim emFrom(1) As ActivityParty
Dim eFrom As New ActivityParty
eFrom.PartyId = New EntityReference(Contact.EntityLogicalName, New Guid("7FBC77C9-785B-E311-BA57-D89D67639E24"))
emFrom(0) = eFrom
em.From = emFrom
Dim emTo(1) As ActivityParty
Dim eTo As New ActivityParty
eTo.PartyId = New EntityReference(inv.CustomerId.LogicalName, inv.CustomerId.Id)
emTo(0) = eTo
em.To = emTo
em.Subject = "Invoice: " & inv.InvoiceNumber
em.Description = emailContent
em.RegardingObjectId = New EntityReference(Invoice.EntityLogicalName, New Guid(InvoiceGUID))
Dim emailID As Guid = ser.Create(em)


Once the email has been created you can then create the attachment which should be of type ActivityMimeAttachment and then associate it with the email just created.
Please note that the file you wish to attach must first be converted to an array of bytes

Dim pdfBytes() As Byte = My.Computer.FileSystem.ReadAllBytes(_folderLocation & "testPDF.pdf")
Dim attachment As New ActivityMimeAttachment
attachment.ObjectId = New EntityReference(Email.EntityLogicalName, emailID)
attachment.ObjectTypeCode = Email.EntityLogicalName
attachment.FileName = inv.InvoiceNumber & ".pdf"
attachment.Body = Convert.ToBase64String(pdfBytes)


About the Author

James CTwo is our blogging alter ego for the Dynamics CRM and Web experts here at C2. We have a passion for anything CRM, Web Design or Social Media. We love writing about it! Find us on YouTube & Twitter.

comments powered by Disqus

Our White Papers

Discover the content that matters to you on business transformation. Explore how you can drive customer engagement, empower your team, optimise your businesses and revolutionise your products with the next digital revolution. For more information visit our white paper library.


C2 Newsletter

Our newsletter is sent on a quarterly basis, offering detailed insights into all aspects of business transformation with Microsoft cloud technologies. We also promote upcoming events and special offers throughout the year. Sign up to get involved today.

Dynamics 365 Office 365 Power BI Silver Partner