[SalesForce] Insert Attachment into Visualforce Email Template

this question: says that it is "hard" to put a component inside a visualforce email template because ' needs to be a child of component.'. Yet, is there a way to make this work?

We also need to stick to using the visualforce email template and cannot send the email in a different way. The object on which the email template is running has attachments. How can this be done?

Best Answer

I don't think you can do it with pure email template, you'll need some Apex, as suggested in other answers.

<messaging:emailTemplate> complains as soon as you'd try to stick <apex:repeat> in there (for example to create <messaging:attachment> nodes in a loop).

Even if you could - try referring to {!relatedTo.Attachments[0].Body} somewhere (can be in the plaintextBody tag), you'll get an error:

Binary fields cannot be selected in join queries

I think the closest it can get is to create the links to attachments (and if I recall correctly - SF converts attachments > 3 MB to links anyway).

<messaging:emailTemplate subject="hello" recipientType="Contact" relatedToType="Opportunity">
<messaging:htmlEmailBody >
    <p>This will list link to attachments... it's not a perfect solution but it's something.</p>

    <apex:repeat value="{!relatedTo.Attachments}" var="a">
    <p><a href="{!URLFOR($Action.Attachment.Download, a)}">{!a.Name}</a> ({!a.BodyLength} B)</p>
    </apex:repeat>
</messaging:htmlEmailBody>
<messaging:plainTextEmailBody >
    <apex:repeat value="{!relatedTo.Attachments}" var="a">
        {!a.Name} {!a.ContentType} {!a.Body} <!-- this "Body" reference causes the compilation to fail -->
    </apex:repeat>
</messaging:plainTextEmailBody>

<!--
<messaging:attachment filename="{!relatedTo.Attachments[0].Name}" renderAs="{!relatedTo.Attachments[0].ContentType}">
 {!relatedTo.Attachments[0].Body}  :(
</messaging:attachment>
-->
</messaging:emailTemplate>
Related Topic