Send Email with Attachment Custom Save Action
I was surprised that Web Forms for Marketers does not come with a send email with attachment Save Action by out of the box. Fortunately it can be achieved with custom code based on the existing Send Email Save Action.
I had a few requirements the client wanted me to stick to;
- The form would have to exist in Web Forms for Marketers so email addresses can be captured
- The user must receive the file from the Media Library as an attachment in the response email upon completing the Form and not a link to a file on the website
- Content Editors must have the ability to choose what attachment is sent per instance of the Form.
Creating a Custom Field Type in Web Form for Marketers
The Send Email Editor only allows Media Items to be linked in the Email means another approach is needed. It is possible to programmatically to create attachment from the link but brings the headache of Content Editors tagging the links they want to be attachments.
Therefore I decided to create a custom Web Forms for Marketers field that would allow the Content Editor to choose a Media Library file via the Form Designer but be hidden to end users and not surface the chosen file(s);
By implementing the Sitecore.Form.Web.UI.Controls.List control will allow Content Editors to choose the source of the Media Items, define if one or more Media Items are to attached and then select which ones.
To add the new Web Form for Marketers Field, in the Content Editor browse to the path
/sitecore/system/Modules/Web Forms for Marketers/Settings/Field Types/Custom and insert a new Item using the Field Type Template entering the Assembly name and Class name into the appropriate fields.
Creating a Custom Save Action to Send Email with Attachment
The Save Action is based on the standard WFFM SendMessage, accessed by decompiling the appropriate dll, and adding additional steps pass the Form Fields to a new method to create the attachments and then add them to the email;
To retrieve the IDs of the MediaItems to be attached is done by using the FormItem, looping through its Fields to find one, or many, fields that Template is our HiddenAttachment custom Field Type and pulling out the Ids in the value property;
Finally its a matter of getting the MediaItems from the list of Ids and creating attachments from its MemoryStream.
And that’s it!
The approach works really well; allowing Content Editors full control of Attachments, send email with attachments on submit of a form and its execution is scalable to allow multiple attachments from multiple fields.