+ Start a Discussion
LBSLBS 

INVALID_CROSS_REFERENCE_KEY in Visual Force email template for community user

I have sort of a strange issue. I have a VF email template which related to Case and recipient type is Contact. Whenever i run this for community user, I'm getting above error, while it perfectly works when I run the code in developer console - anonymous, system admin context. So when I remove the {RelatedTo.casenumber} it works well for community user as well. Field permission for Case object + casenumber field is read only for community user. Here is the email template
<messaging:emailTemplate subject="Subject" recipientType="Contact" relatedToType="Case">
    <messaging:htmlEmailBody >
        <html>
            <head>
              <STYLE type="text/css">
                  body {font-family: arial; color: #000;}
              </STYLE>
            </head>
            <body contenteditable="true">

                <apex:image id="dme_logo" value="sample" />

                <br/>
                <p style="color: #000;">Dear {!recipient.Name}</p>

                <p style="color: #000;">Reference number {!relatedTo.casenumber} </p>              
                <p style="color: #000;">Thanks,<br/>
                USER
                </p>

            </body>
        </html>
    </messaging:htmlEmailBody>
</messaging:emailTemplate>
And the code,
EmailTemplate template = new EmailTemplate();
template = [Select id, name from EmailTemplate where name = 'Template name'];


List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateID(template.Id); 
mail.setTargetObjectId('0037A00000LAdS7');
mail.setSaveAsActivity(false);
mail.setWhatId('5007A000003sQN4QAM');    
mail.setBccSender(false);
mail.setUseSignature(false);
Messaging.sendEmail(mails);
​What can go wrong here guys?