InboundEmail オブジェクト
Apex メールサービスドメインが受信するすべてのメールについて、Salesforce は、そのメールの内容と添付ファイルを含む個別の InboundEmail オブジェクトを作成します。Messaging.InboundEmailHandler インターフェースを実装する Apex クラスを使用して、受信メールメッセージを処理できます。そのクラスで handleInboundEmail メソッドを使用して、InboundEmail オブジェクトにアクセスし、受信メールメッセージの内容、ヘッダー、および添付ファイルの取得と、その他多数の機能を実行することができます。
必要なエディション
| 使用可能なインターフェース: Salesforce Classic (使用できない組織もあります) |
| 使用可能なエディション: Enterprise Edition、Performance Edition、Unlimited Edition、および Developer Edition |
例 1: 取引先責任者の ToDo の作成
受信メールアドレスに基づいて取引先責任者を検索し、新規 ToDo を作成する方法の例は次のとおりです。
public with sharing class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
public Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,
Messaging.InboundEnvelope env){
// Create an InboundEmailResult object for returning the result of the
// Apex Email Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
String myPlainText= '';
// Add the email plain text into the local variable
myPlainText = email.plainTextBody;
// New Task object to be created
Task[] newTask = new Task[0];
// Try to look up any contacts based on the email from address
// If there is more than one contact with the same email address,
// an exception will be thrown and the catch statement will be called.
try {
Contact vCon = [SELECT Id, Name, Email
FROM Contact
WHERE Email = :email.fromAddress
WITH USER_MODE
LIMIT 1 ];
// Add a new Task to the contact record we just found above.
newTask.add(new Task(Description = myPlainText,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now()+1,
WhoId = vCon.Id));
// Insert the new Task
insert as user newTask;
System.debug('New Task Object: ' + newTask );
}
// If an exception occurs when the query accesses
// the contact record, a QueryException is called.
// The exception is written to the Apex debug log.
catch (QueryException e) {
System.debug('Query Issue: ' + e);
}
// Set the result to true. No need to send an email back to the user
// with an error message
result.success = true;
// Return the result for the Apex Email Service
return result;
}
}例 2: メールの登録解除
顧客や見込み客にマーケティングメールを送信する会社は、受信者が登録解除するための方法を用意する必要があります。次の例で、メールサービスで登録解除要求を処理する方法を説明します。このコードは、受信メールの件名の「登録解除」という単語を検索します。単語が見つかると、差出人メールアドレスに一致するすべての取引先責任者とリードを検索し、[メール送信除外] 項目 (HasOptedOutOfEmail) を True に設定します。
public with sharing class unsubscribe implements Messaging.inboundEmailHandler{
public Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
Messaging.InboundEnvelope env ) {
// Create an inboundEmailResult object for returning
// the result of the email service.
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
// Create contact and lead lists to hold all the updated records.
List<Contact> lc = new List <contact>();
List<Lead> ll = new List <lead>();
// Convert the subject line to lower case so the program can match on lower case.
String mySubject = email.subject.toLowerCase();
// The search string used in the subject line.
String s = 'unsubscribe';
// Check the variable to see if the word "unsubscribe" was found in the subject line.
Boolean unsubMe;
// Look for the word "unsubcribe" in the subject line.
// If it is found, return true; otherwise, return false.
unsubMe = mySubject.contains(s);
// If unsubscribe is found in the subject line, enter the IF statement.
if (unsubMe == true) {
try {
// Look up all contacts with a matching email address.
for (Contact c : [SELECT Id, Name, Email, HasOptedOutOfEmail
FROM Contact
WHERE Email = :env.fromAddress
AND hasOptedOutOfEmail = false
LIMIT 100]) {
// Add all the matching contacts into the list.
c.hasOptedOutOfEmail = true;
lc.add(c);
}
// Update all of the contact records.
update as user lc;
}
catch (System.QueryException e) {
System.debug('Contact Query Issue: ' + e);
}
try {
// Look up all leads matching the email address.
for (Lead l : [SELECT Id, Name, Email, HasOptedOutOfEmail
FROM Lead
WHERE Email = :env.fromAddress
AND isConverted = false
AND hasOptedOutOfEmail = false
LIMIT 100]) {
// Add all the leads to the list.
l.hasOptedOutOfEmail = true;
ll.add(l);
System.debug('Lead Object: ' + l);
}
// Update all lead records in the query.
update as user ll;
}
catch (System.QueryException e) {
System.debug('Lead Query Issue: ' + e);
}
System.debug('Found the unsubscribe word in the subject line.');
}
else {
System.debug('No Unsuscribe word found in the subject line.' );
}
// Return True and exit.
// True confirms program is complete and no emails
// should be sent to the sender of the unsubscribe request.
result.success = true;
return result;
}
}@isTest
private class unsubscribeTest {
// The following test methods provide adequate code coverage
// for the unsubscribe email class.
// There are two methods, one that does the testing
// with a valid "unsubcribe" in the subject line
// and one the does not contain "unsubscribe" in the
// subject line.
static testMethod void testUnsubscribe() {
// Create a new email and envelope object.
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
// Create a new test lead and insert it in the test method.
Lead l = new lead(firstName='John',
lastName='Smith',
Company='Salesforce',
Email='user@acme.com',
HasOptedOutOfEmail=false);
insert l;
// Create a new test contact and insert it in the test method.
Contact c = new Contact(firstName='john',
lastName='smith',
Email='user@acme.com',
HasOptedOutOfEmail=false);
insert c;
// Test with the subject that matches the unsubscribe statement.
email.subject = 'test unsubscribe test';
env.fromAddress = 'user@acme.com';
// Call the class and test it with the data in the testMethod.
unsubscribe unsubscribeObj = new unsubscribe();
unsubscribeObj.handleInboundEmail(email, env );
}
static testMethod void testUnsubscribe2() {
// Create a new email and envelope object.
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
// Create a new test lead and insert it in the test method.
Lead l = new lead(firstName='john',
lastName='smith',
Company='Salesforce',
Email='user@acme.com',
HasOptedOutOfEmail=false);
insert l;
// Create a new test contact and insert it in the test method.
Contact c = new Contact(firstName='john',
lastName='smith',
Email='user@acme.com',
HasOptedOutOfEmail=false);
insert c;
// Test with a subject that does not contain "unsubscribe."
email.subject = 'test';
env.fromAddress = 'user@acme.com';
// Call the class and test it with the data in the test method.
unsubscribe unsubscribeObj = new unsubscribe();
unsubscribeObj.handleInboundEmail(email, env );
}
}InboundEmail オブジェクト
InboundEmail オブジェクトには、次の項目があります。
InboundEmail.Header オブジェクト
InboundEmail オブジェクトは、InboundEmail.Header オブジェクトに RFC 2822 メールヘッダー情報と次の項目を格納します。
| 名前 | 型 | 説明 |
|---|---|---|
| name | String | Date や Message-ID など、ヘッダーパラメーターの名前。 |
| value | String | ヘッダーの値。 |
InboundEmail.BinaryAttachment オブジェクト
InboundEmail オブジェクトは、InboundEmail.BinaryAttachment オブジェクトにバイナリ添付ファイルを格納します。
バイナリ添付ファイルの例としては、画像、音声、アプリケーション、映像ファイルなどがあります。
InboundEmail.BinaryAttachment オブジェクトには、次の項目があります。
| 名前 | 型 | 説明 |
|---|---|---|
| body | Blob | 添付ファイルの本文。 |
| fileName | String | 添付ファイルの名前。 |
| mimeTypeSubType | String | プライマリおよびサブ MIME タイプ。 |
InboundEmail.TextAttachment オブジェクト
InboundEmail オブジェクトは、InboundEmail.TextAttachment オブジェクトにテキスト添付ファイルを格納します。
テキスト添付ファイルは次のいずれかです。
textの Multipurpose Internet Mail Extension (MIME) タイプの添付ファイル。application/octet-streamの MIME タイプの添付ファイルと、.vcf または .vcs 拡張子で終わるファイル名の添付ファイル。これらはそれぞれtext/x-vcardおよびtext/calendarMIME タイプとして保存されます。
InboundEmail.TextAttachment オブジェクトには、次の項目があります。
InboundEmailResult オブジェクト
InboundEmailResult オブジェクトにより、メールサービスの結果が返されます。このオブジェクトが Null であれば、結果は正常とみなされます。InboundEmailResult オブジェクトには、次の項目があります。

