function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Adelchi PelizzoAdelchi Pelizzo 

Related EmailMessage to Contact

Inbound Email service works ok relating EmailMessage to Case and Account>

Not working for Contact.
FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Related To ID: id value of incorrect type: 0038d00000BozV3AAJ: [RelatedToId]

I tried also EmailMessageRelation object, same behavior:
FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Relation ID: id value of incorrect type: 0018d00000D5eT0AAJ: [RelationId]

Best Answer chosen by Adelchi Pelizzo
Adelchi PelizzoAdelchi Pelizzo
User-added imageUser-added image

All Answers

Adelchi PelizzoAdelchi Pelizzo
/**
 * Created by Adelchi on 18/06/2022.
 * Purpose : (Write a succinct description of this class here.)
 */


global class InboundEmailService implements Messaging.InboundEmailHandler {
    /**
 * Purpose : (Write a succinct description of this method here.)
 * @param (parameter name) (Describe the first parameter here)
 * @param (parameter name) (Do the same for each additional parameter)
 * @return (description of the return value)
 */
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,Messaging.InboundEnvelope envelop){
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        String name = email.fromName;
        String address = email.fromAddress;
        String replyTo = email.inReplyTo;
        List<String> ccAddressList = email.ccAddresses;
        String msgId = email.messageId;
        String body = email.plainTextBody;
        String bodyHTML = email.htmlBody;
        System.debug('service class'+bodyHTML);
        String subj = email.subject;
        Pattern p = Pattern.compile('(\\w){15}');
        Matcher pm = p.matcher( bodyHTML );
        String relatedRecordId;
        if (pm.find())
        {
            List<String>  relatedRecordIdList = pm.group(0).split(':');
            relatedRecordId = pm.group(0);
            Id id = relatedRecordId;
            Schema.SObjectType sobjectType = id.getSobjectType();
            String sOType = sobjectType.getDescribe().getName();
            System.debug(relatedRecordId);
            String q = 'SELECT Id FROM '+sOType+' WHERE Id = '+'\''+relatedRecordId+'\'';
            SObject sObj = Database.query(q);
            System.debug(sObj);
            EmailMessage newMail;
            EmailMessageRelation emailMessageRelation = new EmailMessageRelation();

            if(sOType == 'Contact' || sOType == 'Lead'){
                newMail = new EmailMessage(
                        FromName = name,
                        FromAddress = address,
                        TextBody = body,
                        Status = '0',
                        Subject = subj
                );
                insert newMail;
            } else {
                newMail = new EmailMessage(
                        FromName = name,
                        FromAddress = address,
                        RelatedToId  = sObj.Id,
                        TextBody = body,
                        Status = '0',
                        Subject = subj
                );
                insert newMail;
            }
            emailMessageRelation.EmailMessageId = newMail.Id;
            emailMessageRelation.RelationId = sObj.Id;
//            insert emailMessageRelation;
            List<Attachment> attList = new List<Attachment>();
            if(email.binaryAttachments != null){
                for (Messaging.InboundEmail.BinaryAttachment file : email.binaryAttachments)
                {
                    Attachment attachment = new Attachment();
                    attachment.Name = file .fileName;
                    attachment.Body = file .body;
                    attachment.ParentId = newMail.Id;
                    attList .add(attachment);
                }
                if(attList .size()>0)
                {
                    insert attList;
                }
            }
        }
        return null;
    }
}

 
Adelchi PelizzoAdelchi Pelizzo
User-added imageUser-added image
This was selected as the best answer