Newer Version Available
Using the InboundEmail Object
For every email the Apex email service domain receives, Salesforce creates a separate InboundEmail object that contains the contents and attachments of that email. You can use Apex classes that implement the Messaging.InboundEmailHandler interface to handle an inbound email message. Using the handleInboundEmail method in that class, you can access an InboundEmail object to retrieve the contents, headers, and attachments of inbound email messages, as well as perform many functions.
Example 1: Create Tasks for Contacts
The following is an example of how you can look up a contact based on the inbound email address and create a new task.
1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
18
19 global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,
20 Messaging.InboundEnvelope env){
21
22 // Create an InboundEmailResult object for returning the result of the
23 // Apex Email Service
24 Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
25
26 String myPlainText= '';
27
28 // Add the email plain text into the local variable
29 myPlainText = email.plainTextBody;
30
31 // New Task object to be created
32 Task[] newTask = new Task[0];
33
34 // Try to look up any contacts based on the email from address
35 // If there is more than one contact with the same email address,
36 // an exception will be thrown and the catch statement will be called.
37 try {
38 Contact vCon = [SELECT Id, Name, Email
39 FROM Contact
40 WHERE Email = :email.fromAddress
41 LIMIT 1];
42
43 // Add a new Task to the contact record we just found above.
44 newTask.add(new Task(Description = myPlainText,
45 Priority = 'Normal',
46 Status = 'Inbound Email',
47 Subject = email.subject,
48 IsReminderSet = true,
49 ReminderDateTime = System.now()+1,
50 WhoId = vCon.Id));
51
52 // Insert the new Task
53 insert newTask;
54
55 System.debug('New Task Object: ' + newTask );
56 }
57 // If an exception occurs when the query accesses
58 // the contact record, a QueryException is called.
59 // The exception is written to the Apex debug log.
60 catch (QueryException e) {
61 System.debug('Query Issue: ' + e);
62 }
63
64 // Set the result to true. No need to send an email back to the user
65 // with an error message
66 result.success = true;
67
68 // Return the result for the Apex Email Service
69 return result;
70 }
71}