Loading
メールアドレスがデフォルトのログイン方式となります 続きを読む
コードを使用した Salesforce の拡張
InboundEmail オブジェクト

InboundEmail オブジェクト

Apex メールサービスドメインが受信するすべてのメールについて、Salesforce は、そのメールの内容と添付ファイルを含む個別の InboundEmail オブジェクトを作成します。Messaging.InboundEmailHandler インターフェースを実装する Apex クラスを使用して、受信メールメッセージを処理できます。そのクラスで handleInboundEmail メソッドを使用して、InboundEmail オブジェクトにアクセスし、受信メールメッセージの内容、ヘッダー、および添付ファイルの取得と、その他多数の機能を実行することができます。

必要なエディション

使用可能なインターフェース: Salesforce Classic (使用できない組織もあります)
使用可能なエディション: Enterprise Edition、Performance Edition、Unlimited Edition、および Developer Edition
メモ
メモ Apex メールサービスについては、「メールサービス」を参照してください。

例 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 オブジェクトには、次の項目があります。

名前 型 説明
binaryAttachments InboundEmail.BinaryAttachment[]

そのメールで受信したバイナリ添付ファイルのリスト (存在する場合)。

バイナリ添付ファイルの例としては、画像、音声、アプリケーション、映像ファイルなどがあります。

ccAddresses String[] カーボンコピー (CC) アドレスのリスト (存在する場合)。
fromAddress String [送信者] 項目に表示されるメールアドレス。
fromName String [送信者] 項目に表示される名前 (存在する場合)。
headers InboundEmail.Header[]

メールの RFC 2822 ヘッダーのリスト。具体的なヘッダーは次のとおりです。

  • 送信元
  • カスタムヘッダー
  • メッセージ ID
  • 日付
htmlBody String メールの HTML 版 (送信者が指定した場合)。
htmlBodyIsTruncated Boolean HTML 本文テキストを切り捨てる (true) か、そのままにする (false) かを示します。
inReplyTo String 受信メールの In-Reply-To 項目。この返信メールの相手となるメール (親メール) を示します。親メールまたはメールのメッセージ ID が含まれます。
messageId String メッセージ ID — 受信メールの一意の ID。
plainTextBody String メールのプレーンテキスト版 (送信者が指定した場合)。
plainTextBodyIsTruncated Boolean 本文プレーンテキストを切り捨てる (true) か、そのままにする (false) かを示します。
references String[] 受信メールの References 項目。メールスレッドを示します。親メールの References 項目とメッセージ ID 項目、場合によっては In-Reply-To 項目が含まれます。
replyTo String

reply-to ヘッダーに表示されるメールアドレス。

reply-to ヘッダーが存在しない場合、fromAddress 項目と同じになります。

subject String メールの件名 (存在する場合)。
textAttachments InboundEmail.TextAttachment[]

そのメールで受信したテキスト添付ファイルのリスト (存在する場合)。

テキスト添付ファイルは次のいずれかです。

  • text の Multipurpose Internet Mail Extension (MIME) タイプの添付ファイル。
  • application/octet-stream の MIME タイプの添付ファイルと、.vcf または .vcs 拡張子で終わるファイル名の添付ファイル。これらはそれぞれ text/x-vcard および text/calendar MIME タイプとして保存されます。
toAddresses String[] [宛先] 項目に表示されるメールアドレス。

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/calendar MIME タイプとして保存されます。

InboundEmail.TextAttachment オブジェクトには、次の項目があります。

名前 型 説明
body String 添付ファイルの本文。
bodyIsTruncated Boolean 添付ファイルの本文テキストを切り捨てる (true) か、そのままにする (false) かを示します。
charset String [body] 項目の元の文字セット。body は、Apex メソッドに入力されるときに UTF-8 でエンコードし直されます。
fileName String 添付ファイルの名前。
mimeTypeSubType String プライマリおよびサブ MIME タイプ。

InboundEmailResult オブジェクト

InboundEmailResult オブジェクトにより、メールサービスの結果が返されます。このオブジェクトが Null であれば、結果は正常とみなされます。InboundEmailResult オブジェクトには、次の項目があります。

名前 型 説明
success Boolean

メールが正常に処理されたかどうかを示す値。

false の場合は、Salesforce が受信メールを拒否し、[メッセージ] 項目で指定されているメッセージを含む返信メールを元の送信者に送信します。

message String Salesforce が返信メールの本文で返すメッセージ。この項目には、[成功] 項目で返された値に関係なく、テキストを取り込むことができます。

InboundEnvelope オブジェクト

InboundEnvelope オブジェクトには、受信メールに関連するエンベロープ情報が保管され、次の項目があります。

名前 型 説明
toAddress String [宛先] 項目に表示される名前 (存在する場合)。
fromAddress String [差出人] 項目に表示される名前 (存在する場合)。
 
読み込み中
Salesforce Help | Article