Loading
以程式碼增強 Salesforce
InboundEmail 物件

InboundEmail 物件

對於 Apex 電子郵件服務網域收到的每一封電子郵件,Salesforce 都會建立單獨的 InboundEmail 物件,其中包含該電子郵件的內容及附件。您可以使用實作 Messaging.InboundEmailHandler 介面的 Apex 類別來處理輸入電子郵件訊息。使用該類別中的 handleInboundEmail 方法,您可以存取 InboundEmail 物件,以 ⁇ 取輸入電子郵件訊息的內容、標題和附件,以及執行許多功能。

必要版本

提供版本:Salesforce Classic (並非所有組織皆適用)
提供版本:EnterprisePerformanceUnlimitedDeveloper Edition
備註
備註 如需關於 Apex 電子郵件服務的資訊,請參閱電子郵件服務

範例 1:建立連絡人的工作

以下是如何根據內送電子郵件地址尋找連絡人及建立新工作的範例。

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:處理取消訂閱的電子郵件

將行銷電子郵件寄給其客戶及潛在客戶的公司,需要提供一種能讓收件者取消訂閱的方式。下列範例說明電子郵件服務如何處理取消訂閱要求。程式碼會搜尋輸入電子郵件的主旨行是否有「unsubscribe」字樣。如果找到該字,程式碼會尋找符合「寄件者」電子郵件地址的所有連絡人和商機,並將「電子郵件取消選取」欄位 (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 字串 出現在「寄件者」欄位的電子郵件地址。
fromName 字串 出現在「寄件者」欄位的名稱 (如果有的話)。
headers InboundEmail.Header[]

電子郵件的 RFC 2822 標題清單,包括:

  • 接收來源
  • Custom headers
  • Message-ID
  • 日期
htmlBody 字串 電子郵件的 HTML 版本 (如果寄件者有指定)。
htmlBodyIsTruncated 布林值 表示是否截斷 HTML 內文文字 (true) (false)。
inReplyTo 字串 傳入電子郵件的 In-Reply-To 欄位。識別此電子郵件回覆的原始電子郵件 (父系電子郵件)。含有父系電子郵件或電子郵件的 Message-ID。
messageId 字串 Message-ID 是傳入電子郵件的唯一識別碼。
plainTextBody 字串 電子郵件的純文字版本 (如果寄件者有指定)。
plainTextBodyIsTruncated 布林值 表示是否截斷純文字內文文字 (true) (false)。
references String [] 傳入電子郵件的 References 欄位。識別電子郵件的執行緒。包含父系電子郵件的 References 和 Message ID 清單,可能也包含 In-Reply-To 欄位。
replyTo 字串

出現在 reply-to 標題的電子郵件地址。

如果沒有 reply-to 標題,此欄位與「fromAddress」欄位完全相同。

subject 字串 電子郵件的主旨行 (如果有的話)。
textAttachments InboundEmail.TextAttachment[]

與電子郵件一起收到的文字附件清單 (如果有的話)。

文字附件可以是下列任何一種:

  • 具有多用途網際網路郵件延伸 (MIME) 類型之 text 的附件
  • 具有 MIME 類型 application/octet-stream 的附件,以及以 .vcf.vcs 副檔名結尾的檔案名稱。這些項目會分別儲存為 text/x-vcardtext/calendar MIME 類型。
toAddresses String[] 出現在「收件者」欄位的電子郵件地址。

InboundEmail.Header 物件

InboundEmail 物件將 RFC 2822 電子郵件標題資訊儲存在 InboundEmail.Header 物件中,包含下列欄位。

名稱 類型 描述
name 字串 標頭參數的名稱,例如 DateMessage-ID
value 字串 標題值。

InboundEmail.BinaryAttachment 物件

InboundEmail 物件將雙位元附件儲存在 InboundEmail.BinaryAttachment 物件中。

雙位元附件的範例包含影像、音訊、應用程式,和視訊檔。

InboundEmail.BinaryAttachment 物件具有下列欄位。

名稱 類型 描述
body Blob 附件的內文。
fileName 字串 附加檔案的名稱。
mimeTypeSubType 字串 主要及次要 MIME 類型。

InboundEmail.TextAttachment 物件

InboundEmail 物件將文字附件儲存在 InboundEmail.TextAttachment 物件中。

文字附件可以是下列任何一種:

  • 具有多用途網際網路郵件延伸 (MIME) 類型之 text 的附件
  • 具有 MIME 類型 application/octet-stream 的附件,以及以 .vcf.vcs 副檔名結尾的檔案名稱。這些項目會分別儲存為 text/x-vcardtext/calendar MIME 類型。

An InboundEmail.TextAttachment 物件具有下列欄位。

名稱 類型 描述
body 字串 附件的內文。
bodyIsTruncated 布林值 表示是否截斷附件內文文字 (true) (false)。
charset 字串 內文欄位的原始字元集。內文輸入到 Apex 方法時,會被重新編碼為 UTF-8。
fileName 字串 附加檔案的名稱。
mimeTypeSubType 字串 主要及次要 MIME 類型。

InboundEmailResult 物件

InboundEmailResult 物件用來傳回電子郵件服務結果。如果此物件為 null,結果會被認定為成功。The InboundEmailResult object 物件具有下列欄位。

名稱 類型 描述
success 布林值

指出是否成功處理電子郵件的值。

如果是 false,則 Salesforce 會拒絕輸入電子郵件,並傳送回覆電子郵件給原始寄件者,其中包含在「訊息」 欄位中指定的訊息。

message 字串 Salesforce 在回覆電子郵件內文中傳回的訊息。此欄位可填入和 Success 欄位傳回值無關的文字。

InboundEnvelope 物件

InboundEnvelope 物件儲存與輸入電子郵件相關的信封資訊且具有下列欄位。

名稱 類型 描述
toAddress 字串 出現在信封的收件者欄位的名稱 (如果有的話)。
fromAddress 字串 出現在信封的寄件者欄位的名稱 (如果有的話)。
 
正在載入
Salesforce Help | Article