• Steven Downey
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Hi All,

I hope you could assist me in achieving my goal here. I am not a coder and just following the patterns on existing codes anywhere in the site. My goals are:
  • Create Opportunity record from incoming emails. (create something like e2c)
  • Create Contact record if there are no matching emails in the system and populate the custom Contact lookup in Opp.
  • When user send an email from that Opportunity record and customer replies back, the response should be attached to existing Opportunity.
Here's what I have:
  • Custom Contact Lookup in Opportunity
  • ThreadID field in Opportunity which I use in Email Subject and Description:

Here is the existing code:

global class OpportunityCreation implements Messaging.InboundEmailHandler {

  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

     Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    
       Contact vCon = [Select Id, Name, Email, AccountId
       From Contact 
       Where Email = :email.fromAddress
       Limit 1];

    Opportunity opportunity = new Opportunity();
    opportunity.Name = email.Subject;
    opportunity.StageName = 'Prospecting';
    opportunity.CloseDate = Date.today();
    opportunity.Email_Body__c = email.plainTextBody;
    opportunity.Contact_Name__c = vCon.Id;
    opportunity.AccountId = vCon.AccountId;
    insert opportunity;
    
       System.debug('====> Created opportunity '+opportunity.Id);
       
      
if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created opportunity record
        attachment.ParentId = opportunity.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
      }
    }
  
    return result;

  }

}

Current behavior of the code:
  • It doesn't create an Opportunity if there are no matching email address in the system. (Expected: create Opportunity + Contact if there are no matching email in the system)
  • Email Threads like email to case doesn't work.
Any assistance is greatly appreciated.

  •