There are two ways to do it:
- Without storing the decrypted document on cloud
- Store it in decrypted form as an attachment.
Below are the codes for both of the things:
APEX:
//Using future method here to avoid CPU time limit exception
// Below method do not store anything on cloud and sends email with decrypted document to an
// email Id
public static void sendDecryptedAtt(String accId,Blob key, String emailId)
{
List<Attachment> attList=[Select id,name,body from Attachment where parentId=:accId limit 1];
if(attList.size() > 0){
Blob decrypted = Crypto.decryptWithManagedIV('AES256', key, attList[0].body);
String blobString=decrypted.toString();
Blob doc=EncodingUtil.base64decode(blobString);
String fileName=accAtt.name;
sendEmail(doc,emailId,fileName);
createAtt(doc, fileName, accId);
}
}
// below method sends email to the given email address
Public Static Void sendEmail(Blob attachmentFile, String emailId,String fileName)
{
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(fileName);
efa.setBody(attachmentFile);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setSubject('Decrypted File: '+ fileName);
String[] emails=new List<String> {emailId};
email.setToAddresses( emails);
email.setPlainTextBody('Hi,\n\nPlease find attached decrypted document.\n\nThanks');
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[ {email});
}
//Below method creates an attachment in the Salesforce with decrypted content
Public Static Void createAtt(Blob attachmentFile, String fileName, String accId)){
Attachment att=new Attachment();
att.name = 'Decrypted_'+fileName;att.body = attachmentFile;
att.parentId = accId;
insert att;
}
Above code works for all kind of documents. Encryption technique is present in my previous posts.
No comments:
Post a Comment