I am getting an attachment via a Salesforce email service and in the Email service apex class logic, I query the user object by the email from address and set the ContentVersion owner as the user coming from the Query.
I am getting this error while performing this operation.
INVALID_STATUS, Documents in a user's private library must always be owned by that user.: [OwnerId]
Here is my code :
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
//Get users for the incoming email address and also community user
List<User> lstUsersFromCommunity = [SELECT Id
FROM User
WHERE Profile.UserLicense.Name = 'Partner Community';
AND Email =: email.fromAddress];
//Process only if the incoming email address is belongs to a valid community user
if(lstUsersFromCommunity.size() > 0){
//Get the user from the results list
User user = lstUsersFromCommunity.get(0);
try{
//Create a list of ContentVersion to store new ContentVersion records
List<ContentVersion> lstVersion = new List<ContentVersion>();
//Iterate over the incoming email attachments
for (Messaging.Inboundemail.BinaryAttachment binaryAttachment : email.binaryAttachments) {
//New ContentVersion record
ContentVersion newContentVersion = new ContentVersion();
newContentVersion.versionData = binaryAttachment.body;
newContentVersion.OwnerId = user.Id;
newContentVersion.ContentLocation = 'S';
newContentVersion.SharingOption = 'A';
newContentVersion.Origin = 'H';
newContentVersion.title = email.subject;
newContentVersion.pathOnClient = binaryAttachment.fileName;
lstVersion.Add(newContentVersion);
}
insert lstVersion;
}catch(Exception ex){
System.debug('### EXCEPTION : ' + ex.getLineNumber() + ' : ' + ex.getMessage());
}
}else{
//No user in for the from email address
}
return result;
}