I am using email to case and it works really well. I created a trigger to create a contact if it already doesn't exist. My issue is when the trigger obtains the email address, it saves information that isn't regularly in my email address. The regular address is jdoe@company.com. The trigger saves jdoe@company.onmicrosoft.com. This essentially creates a new contact. Does anyone know how to fix this. Here is the snippet where the contact is created:
trigger EmailCaseCreateContactTrigger on Case (before insert) {
List<String> emailAddresses = new List<String>();
//Exclude cases where contact is set
for (Case caseObj :Trigger.new) {
if(caseObj.ContactId == null && caseObj.SuppliedEmail != '') {
emailAddresses.add(caseObj.SuppliedEmail);
}
}
//Query to see if the contacts already exist.
List<Contact> listContacts = [SELECT Id, Email FROM Contact WHERE Email in :emailAddresses];
Set<String> takenEmails = new Set<String>();
for (Contact c:listContacts) {
takenEmails.add(c.Email);
}
Map<String, Contact> emailToContactMap = new Map<String, Contact>();
List<Case> casesToUpdate = new List<Case>();
for (Case caseObj :Trigger.new) {
if (caseObj.ContactId == null &&
caseObj.SuppliedName != null &&
caseObj.SuppliedEmail != null &&
caseObj.SuppliedName != '' &&
!caseObj.SuppliedName.contains('@') &&
caseObj.SuppliedEmail != '' &&
!takenEmails.contains(caseObj.SuppliedEmail)) {
//Create contact for case that was created with a null contact.
String[] nameParts = caseObj.SuppliedName.split(' ',2);
if (nameParts.size() == 2) {
Contact cont = new Contact(FirstName = nameParts[0],
LastName = nameParts[1],
Email = caseObj.SuppliedEmail,
Autocreated__c = true,
Business_ID__c = '0000');
emailToContactMap.put(caseObj.SuppliedEmail,cont);
casesToUpdate.add(caseObj);
}
}
}
List<Contact> newContacts = emailToContactMap.values();
insert newContacts;
for (Case caseObj :casesToUpdate) {
Contact newContact = emailToContactMap.get(caseObj.SuppliedEmail);
caseObj.ContactId = newContact.Id;
}
}
!String.isEmpty(caseObj.SuppliedName)
and (2) if the supplied name is something likeDick Van Dyke
, then you'll not create a Contact. Same problem if the supplied name isBono
orPrince
. – cropredy Feb 5 '15 at 0:29