Thursday, January 21, 2010

Email -> Open attachment file stored as blob data

The following code explains how to open the file attachment which is stored as blob data in database.
Parameter: emailItemId which is used to identify the attachment saved in SysOutgoingEmailData table.
This method can be called from a button click in the "Email-sending status" from from Admin-> Periodic->Email processing


void ShowAttachment(SysEmailItemId _emailItemId)
{
    SysOutgoingEmailData outgoingEmailData;
    str tempPath;
    BinData binData;
    FileIOPermission fileIOPermission;
    str filePathName;
    int retVal;
    ;

    fileIOPermission = new FileIOPermission('','r');
    fileIOPermission.assert();

    //BP Deviation Documented
    //tempPath = WinApiServer::getTempPath();

    tempPath = WinApi::getTempPath();

    CodeAccessPermission::revertAssert();

    // add embedded objects and attachments to the message
    
select outgoingEmailData
        index hint EmailDataIdx
        where outgoingEmailData.EmailItemId == _emailItemId; //OutgoingEmail.EmailItemId;

    if (SysEmailDistributor::validateFileName(outgoingEmailData.FileName))
    {
        binData = new BinData();

        binData.setData(outgoingEmailData.Data);

        if (outgoingEmailData.EmailDataType == SysEmailDataType::Embedded)
            // embedded images are renamed to ensure uniqueness
           filePathName = tempPath + int642str(outgoingEmailData.EmailItemId) + '_' + int2str(outgoingEmailData.DataId);
        else
           // attachment cannot be renamed
           filePathName = tempPath + outgoingEmailData.FileName;

        if (outgoingEmailData.FileExtension)
           filePathName = filePathName + outgoingEmailData.FileExtension;

        fileIOPermission = new FileIOPermission(filePathName,'w');
        fileIOPermission.assert();

        //BP Deviation Documented
        binData.saveFile(filePathName);

        CodeAccessPermission::revertAssert();

        if (outgoingEmailData.FileExtension == ".htm")
           retVal = WinApi::shellExecute(filePathName,"","","",1,false);
        else
        {
           retVal = WinApi::shellExecute(filePathName,"","","",1,true);

           fileIOPermission = new FileIOPermission(filePathName,'w');
           fileIOPermission.assert();

           //BP Deviation Documented
           WinApi::deleteFile(filePathName);

           CodeAccessPermission::revertAssert();
        }
    }
}