Syntax Highlighter JS

Wednesday, September 12, 2012

Utility Class - Convert Attachment to EmailAttachment

Today's post is going to be a very obvious solution to most developers but is posted here for those learning apex code or those wanting a copy and paste solution.

The use case is that you have created a custom VF page on a site and are using it in a web-to-lead manner but taking it a step further by using a custom controller to send a confirmation email to the submitter.

The form in question just happens to have file attachments that you would like to send out in the confirmation email.   The issue is that the file coming in will be an attachment but you have to use an email attachment object type on your object going out.

I have written a rather simple method to do this:

static public Messaging.Emailfileattachment ConvertFileAttachmentToEmailAttachment(Attachment IncomingFile) { Messaging.Emailfileattachment ReturnEmailAttachment = new Messaging.Emailfileattachment(); if (IncomingFile != null) { if (IncomingFile.body != null) { Blob IncomingFileBodyBlob = IncomingFile.Body; ReturnEmailAttachment.setBody(IncomingFileBodyBlob); } ReturnEmailAttachment.setFileName(IncomingFile.Name); } // body != null return ReturnEmailAttachment; } // ConvertFileAttachmentToEmailAttachment

Right after you insert the attachment(s) you can do a call like this: RelatedBidsEmailAttachment = Util.ConvertFileAttachmentToEmailAttachment(RelatedBidsfile);
And then you can add the attachment(s) to a list: List<Messaging.EmailFileAttachment> FilesToAttachToEmail = new List<Messaging.EmailFileAttachment>(); FilesToAttachToEmail.add(RelatedBidsEmailAttachment);
And finally add them to your email: email.setFileAttachments(FilesToAttachToEmail);

No comments:

Post a Comment