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.
1global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
2
3 global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,
4 Messaging.InboundEnvelope env){
5
6 // Create an InboundEmailResult object for returning the result of the
7 // Apex Email Service
8 Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
9
10 String myPlainText= '';
11
12 // Add the email plain text into the local variable
13 myPlainText = email.plainTextBody;
14
15 // New Task object to be created
16 Task[] newTask = new Task[0];
17
18 // Try to look up any contacts based on the email from address
19 // If there is more than one contact with the same email address,
20 // an exception will be thrown and the catch statement will be called.
21 try {
22 Contact vCon = [SELECT Id, Name, Email
23 FROM Contact
24 WHERE Email = :email.fromAddress
25 LIMIT 1];
26
27 // Add a new Task to the contact record we just found above.
28 newTask.add(new Task(Description = myPlainText,
29 Priority = 'Normal',
30 Status = 'Inbound Email',
31 Subject = email.subject,
32 IsReminderSet = true,
33 ReminderDateTime = System.now()+1,
34 WhoId = vCon.Id));
35
36 // Insert the new Task
37 insert newTask;
38
39 System.debug('New Task Object: ' + newTask );
40 }
41 // If an exception occurs when the query accesses
42 // the contact record, a QueryException is called.
43 // The exception is written to the Apex debug log.
44 catch (QueryException e) {
45 System.debug('Query Issue: ' + e);
46 }
47
48 // Set the result to true. No need to send an email back to the user
49 // with an error message
50 result.success = true;
51
52 // Return the result for the Apex Email Service
53 return result;
54 }
55}