InboundEmail オブジェクトの使用
Apex メールサービスドメインが受信するすべてのメールについて、Salesforce は、そのメールの内容と添付ファイルを含む個別の InboundEmail オブジェクトを作成します。Messaging.InboundEmailHandler インターフェースを実装する Apex クラスを使用して、受信メールメッセージを処理できます。そのクラスで handleInboundEmail メソッドを使用して、InboundEmail オブジェクトにアクセスし、受信メールメッセージの内容、ヘッダー、および添付ファイルの取得と、その他多数の機能を実行することができます。
例 1: 取引先責任者の ToDo の作成
受信メールアドレスに基づいて取引先責任者を検索し、新規 ToDo を作成する方法の例は次のとおりです。
1public with sharing class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
2
3 public 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 WITH USER_MODE
26 LIMIT 1];
27
28 // Add a new Task to the contact record we just found above.
29 newTask.add(new Task(Description = myPlainText,
30 Priority = 'Normal',
31 Status = 'Inbound Email',
32 Subject = email.subject,
33 IsReminderSet = true,
34 ReminderDateTime = System.now()+1,
35 WhoId = vCon.Id));
36
37 // Insert the new Task
38 insert as user newTask;
39
40 System.debug('New Task Object: ' + newTask );
41 }
42 // If an exception occurs when the query accesses
43 // the contact record, a QueryException is called.
44 // The exception is written to the Apex debug log.
45 catch (QueryException e) {
46 System.debug('Query Issue: ' + e);
47 }
48
49 // Set the result to true. No need to send an email back to the user
50 // with an error message
51 result.success = true;
52
53 // Return the result for the Apex Email Service
54 return result;
55 }
56}例 2: メールの登録解除
顧客や見込み客にマーケティングメールを送信する会社は、受信者が登録解除するための方法を用意する必要があります。次の例で、メールサービスで登録解除要求を処理する方法を説明します。このコードは、受信メールの件名の「登録解除」という単語を検索します。単語が見つかると、差出人メールアドレスに一致するすべての取引先責任者とリードを検索し、[メール送信除外] 項目 (HasOptedOutOfEmail) を True に設定します。
1public with sharing class unsubscribe implements Messaging.inboundEmailHandler{
2
3 public Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
4 Messaging.InboundEnvelope env ) {
5
6 // Create an inboundEmailResult object for returning
7 // the result of the email service.
8 Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
9
10 // Create contact and lead lists to hold all the updated records.
11 List<Contact> lc = new List <contact>();
12 List<Lead> ll = new List <lead>();
13
14 // Convert the subject line to lower case so the program can match on lower case.
15 String mySubject = email.subject.toLowerCase();
16 // The search string used in the subject line.
17 String s = 'unsubscribe';
18
19 // Check the variable to see if the word "unsubscribe" was found in the subject line.
20 Boolean unsubMe;
21 // Look for the word "unsubcribe" in the subject line.
22 // If it is found, return true; otherwise, return false.
23 unsubMe = mySubject.contains(s);
24
25 // If unsubscribe is found in the subject line, enter the IF statement.
26
27 if (unsubMe == true) {
28
29 try {
30
31 // Look up all contacts with a matching email address.
32
33 for (Contact c : [SELECT Id, Name, Email, HasOptedOutOfEmail
34 FROM Contact
35 WHERE Email = :env.fromAddress
36 AND hasOptedOutOfEmail = false
37 WITH USER_MODE
38 LIMIT 100]) {
39
40 // Add all the matching contacts into the list.
41 c.hasOptedOutOfEmail = true;
42 lc.add(c);
43 }
44 // Update all of the contact records.
45 update as user lc;
46 }
47 catch (System.QueryException e) {
48 System.debug('Contact Query Issue: ' + e);
49 }
50
51 try {
52 // Look up all leads matching the email address.
53 for (Lead l : [SELECT Id, Name, Email, HasOptedOutOfEmail
54 FROM Lead
55 WHERE Email = :env.fromAddress
56 AND isConverted = false
57 AND hasOptedOutOfEmail = false
58 WITH USER_MODE
59 LIMIT 100]) {
60 // Add all the leads to the list.
61 l.hasOptedOutOfEmail = true;
62 ll.add(l);
63
64 System.debug('Lead Object: ' + l);
65 }
66 // Update all lead records in the query.
67 update as user ll;
68 }
69
70 catch (System.QueryException e) {
71 System.debug('Lead Query Issue: ' + e);
72 }
73
74 System.debug('Found the unsubscribe word in the subject line.');
75 }
76 else {
77 System.debug('No Unsuscribe word found in the subject line.' );
78 }
79 // Return True and exit.
80 // True confirms program is complete and no emails
81 // should be sent to the sender of the unsubscribe request.
82 result.success = true;
83 return result;
84 }
85}1@isTest
2private class unsubscribeTest {
3 // The following test methods provide adequate code coverage
4 // for the unsubscribe email class.
5 // There are two methods, one that does the testing
6 // with a valid "unsubcribe" in the subject line
7 // and one the does not contain "unsubscribe" in the
8 // subject line.
9 static testMethod void testUnsubscribe() {
10
11 // Create a new email and envelope object.
12 Messaging.InboundEmail email = new Messaging.InboundEmail() ;
13 Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
14
15 // Create a new test lead and insert it in the test method.
16 Lead l = new lead(firstName='John',
17 lastName='Smith',
18 Company='Salesforce',
19 Email='user@acme.com',
20 HasOptedOutOfEmail=false);
21 insert l;
22
23 // Create a new test contact and insert it in the test method.
24 Contact c = new Contact(firstName='john',
25 lastName='smith',
26 Email='user@acme.com',
27 HasOptedOutOfEmail=false);
28 insert c;
29
30 // Test with the subject that matches the unsubscribe statement.
31 email.subject = 'test unsubscribe test';
32 env.fromAddress = 'user@acme.com';
33
34 // Call the class and test it with the data in the testMethod.
35 unsubscribe unsubscribeObj = new unsubscribe();
36 unsubscribeObj.handleInboundEmail(email, env );
37
38 }
39
40 static testMethod void testUnsubscribe2() {
41
42 // Create a new email and envelope object.
43 Messaging.InboundEmail email = new Messaging.InboundEmail();
44 Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
45
46 // Create a new test lead and insert it in the test method.
47 Lead l = new lead(firstName='john',
48 lastName='smith',
49 Company='Salesforce',
50 Email='user@acme.com',
51 HasOptedOutOfEmail=false);
52 insert l;
53
54 // Create a new test contact and insert it in the test method.
55 Contact c = new Contact(firstName='john',
56 lastName='smith',
57 Email='user@acme.com',
58 HasOptedOutOfEmail=false);
59 insert c;
60
61 // Test with a subject that does not contain "unsubscribe."
62 email.subject = 'test';
63 env.fromAddress = 'user@acme.com';
64
65 // Call the class and test it with the data in the test method.
66 unsubscribe unsubscribeObj = new unsubscribe();
67 unsubscribeObj.handleInboundEmail(email, env );
68 // Assert that the Lead and Contact have been unsubscribed
69 Lead updatedLead = [Select Id, HasOptedOutOfEmail from Lead where Id = :l.Id];
70 Contact updatedContact = [Select Id, HasOptedOutOfEmail from Contact where Id = :c.Id];
71 Assert.isTrue(l.HasOptedOutOfEmail);
72 Assert.isTrue(c.HasOptedOutOfEmail);
73 }
74}