Test method for Email Services with Attachments | Salesforce Developers Blog

If you are new to Force.com Email Services and having a hard time writing test methods for your Apex code, this code sample might help you get started.

You can receive email attachments with inbound emails and often you want to build Apex code that uses the attachments. How do I create an inline attachments for the test method?

The example below shows you how you can create a new email message and assign the attachments to it. You can also find the code sample here.

static testMethod void myTestMethod() {

   // Create a new email, envelope object and Attachment
   Messaging.InboundEmail email = new Messaging.InboundEmail();
   Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
   Messaging.InboundEmail.BinaryAttachment inAtt = new Messaging.InboundEmail.BinaryAttachment();

   email.subject = 'test';
   env.fromAddress = 'user@acme.com';

   // set the body of the attachment
   inAtt.body = blob.valueOf('test');
   inAtt.fileName = 'my attachment name';
   inAtt.mimeTypeSubType = 'plain/txt';

   email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] {inAtt };

   // call the class and test it with the data in the testMethod
   myTestObj emailServiceObj = new myTestObj();
   emailServiceObj.handleInboundEmail(email, env );                     


Stay up to date with the latest news from the Salesforce Developers Blog