Friday, July 17, 2009

Add / Upload attachment to Email activity in CRM 4.0/ 3.0

public void AddAttachmentToEmailActivity(string emailActId, string PDFFileNameName)
{
//Add an attachment
string currentPath = txtPath.Text;
Directory.SetCurrentDirectory(currentPath );

// Check to see if File exists
activitymimeattachment attachment = new activitymimeattachment();

if (File.Exists(currentPath + "\\" + PDFFileNameName.ToString() + ".pdf"))
{
// Get mimeType for File extension
string ext = System.IO.Path.GetExtension(currentPath + "\\" + PDFFileNameName.ToString() + ".pdf").ToLower();
string mimeType = string.Empty;
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();

//New Filestream Code for MS Word .doc and .docx extensions and PDF files .pdf extension
FileInfo pointer = new FileInfo(currentPath + "\\" + PDFFileNameName.ToString() + ".pdf");
FileStream fileStream = pointer.OpenRead();
byte[] byteData = new byte[(int)fileStream.Length];
fileStream.Read(byteData, 0, (int)fileStream.Length);
string encodedData = System.Convert.ToBase64String(byteData);
fileStream.Flush();
fileStream.Close();

attachment.activityid = new Lookup();
attachment.activityid.Value =new Guid(emailActId);
attachment.activityid.type = EntityName.email.ToString();
attachment.filename = PDFFileNameName.ToString() + ".pdf";
attachment.attachmentnumber = new CrmNumber();
attachment.attachmentnumber.Value = 1;
attachment.body = encodedData;
attachment.mimetype = mimeType;

service = CLM_CRM_Service.GetCrmService();

// Create the Attachment in CRM.
Guid attachmentId = service.Create(attachment);

}

}

No comments: