I would love a bit of advice on using the InboundEmailHandler service.
Seems simple. Process:
- Email to generated address from email service
- Apex Class checks if a contact with the details exist
- if list is null then create a Account <- Contact <- Opportunity all linked.
The Contact and Account get created fine and are linked, Then the Opportunity__c gets created but the look-up to Account and Contact aren't populated with the newly inserted records.
global Messaging.InboundEmailResult handleInboundEmail(
Messaging.InboundEmail email,
Messaging.InboundEnvelope envelope
) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
System.debug('---Inside handleInbound------');
try{
String htmlBodyTemplate = email.htmlBody;
String emailBody = htmlBodyTemplate.stripHtmlTags();
String fullname = emailBody.substringBetween('Name: ', 'Email');
String contactemail = emailBody.substringBetween('Email: ', ' ');
String comments = emailBody.substringBetween('Comments: ', 'Remember,');
String phone = emailBody.substringBetween('Phone: ', 'About');
String useremail = envelope.fromAddress;
String propertyAddress = emailBody.substringBetween('Property address: ', 'Property' );
String Search ='%'+propertyAddress+'%';
String assignedto = [SELECT Id FROM user WHERE Email =:useremail AND isActive = true LIMIT 1].Id;
List<Contact> contactEmailList = [SELECT Id,
LastName,
Email,
Description
FROM Contact
WHERE Email =: contactemail
LIMIT 1];
if (contactEmailList.isEmpty()) {
Account accountObj = new Account(
Name = fullname.substring(0,fullname.indexOf(' '))+' '+fullname.substring(fullname.indexOf(' ')));
insert accountObj;
//Create Contact
Contact contactObj = new Contact(
AccountId = accountObj.Id,
FirstName = fullname.substring(0,fullname.indexOf(' ')),
LastName = fullname.substring(fullname.indexOf(' ')),
Description = comments,
Email = contactemail,
LeadSource = 'Email');
//insert Contact
insert contactObj;
Opportunity__c oppObj = new Opportunity__c(
Name = fullname,
Account__c = accountObj.Id,
Contact__c = contactObj.Id,
Description__c = comments,
Source__c = 'Email');
insert oppObj;
}
result.success = true;
}
catch (DmlException e) {
System.debug('Something went wrong ' + e.getMessage());
result.success=false;
}
//result.success = true;
return result;
}
}
Any Help would be great. Cheers