I've developed a custom inbound email handler in order to be used with email-to-case, but, when some criteria are met, I need to "bounce" a custom email to the sender indicating some steps to follow and I need to have the inbound message attached to this "bounce" email.
I'm facing some issues with it, My apex code is something similar to this:
private void sendWarningEmail(){ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {this.inboundEmail.fromAddress}; mail.setToAddresses(toAddresses); mail.setBccSender(false); mail.setUseSignature(false); mail.setSenderDisplayName('Sender Name'); EmailTemplate et = [select Id, Subject, HtmlValue, Body from EmailTemplate where DeveloperName=:'Template']; mail.setTemplateId(et.id); //dummy contact to be the target object Contact c = new Contact(); c.Email = this.inboundEmail.fromAddress; mail.setTargetObjectId(c.Id); //attach the original mail message Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); efa.setFileName(this.inboundEmail.subject); efa.setBody(Blob.valueof(this.inboundEmail.htmlBody)); efa.setContentType('multipart/mixed'); mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); // Send the email you have created. Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); }
I'm not sure about what the problem can be, but even when the attachement is created and added to the "bounced" email, it is "corrupted" or not in the correct format, because it cannot be opened.
What am I missing?
I hope someone can shed some light on this.