2

Is It possible to Send and Receive Email from Account,Lead,Opportunity,Quotes,Case in communities..

I am looking for a working solution for email component in lightning communities.

I need a custom lightning component , which can send the emails from salesforce to any email address.

Once email is send , that information should be saved on that particular salesforce record .

If reply is received by salesforce , that information also i have to maintain in that particular record. I should able to reply to the same email from salesforce.

I checked with inbound and out bound email messages, but I am unable to capture group of conversations and i can't reply for the received email.

enter image description here

Tried to do with email services,But I cannot find the options to reply to particular email as like above screen shot which is in activity History.Below screen shot is for Email Message which is Recieved using email service, enter image description here

Code Used for Email Service to store inbound Messages,above screenshot is for the messages received from my personal email

global class TXP_EmailServiceInbound implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    String myPlainText= '';
    // Add the email plain text into the local variable 
    myPlainText = email.plainTextBody;

    string sss= email.subject;
    string [] a = sss.split('\\(');
    system.debug('a0 ='+ a[0]);
    system.debug('a1 ='+ a[1]);
    string [] bb = a[1].split('\\)');
    system.debug('bb '+bb[0] );
    string subrecid = bb[0] ;

    List<List<sObject>> searchList = [FIND :subrecid IN ALL FIELDS 
                                      RETURNING Account(id),Contact(id),Lead(id)];
    Account[] searchAccounts = (Account[])searchList[0];
    Contact[] searchContacts = (Contact[])searchList[1];
    Lead[] searchLeads = (Lead[]) searchList[2];

    If (subrecid.startsWith('003')){
        Contact vConid = [SELECT Id, Name, Email
                        FROM Contact
                        WHERE id = :subrecid
                        LIMIT 1 ];
           system.debug('bb2345id '+ vConid ); 

        //Add Inbound Email Message for contact
        EmailMessage caseEmailMessage = new EmailMessage();
        caseEmailMessage.ToAddress =  String.join(email.toAddresses, ',');
        //caseEmailMessage.CcAddress =  String.join(email.ccAddresses, ',');
        caseEmailMessage.FromAddress =  email.FromAddress;
        caseEmailMessage.FromName = email.FromName;
        caseEmailMessage.Subject = email.subject;
        caseEmailMessage.status = '3';
        caseEmailMessage.HtmlBody = email.htmlBody;
        System.debug('htmlBody:>>>> ' + email.htmlBody );
        caseEmailMessage.Incoming= True;
        caseEmailMessage.TextBody = email.plainTextBody;
        System.debug('TextBody:>>>>> ' + email.plainTextBody);
        caseEmailMessage.Contact__c = vConid.Id;
        vConid.EmailMessageId__c = email.messageId;
        update vConid;
        insert caseEmailMessage;
        System.debug('Reply Email: ' + caseEmailMessage ); 


        // Add Email Message Relation for id of the sender
        EmailMessageRelation emr = new EmailMessageRelation();
        emr.EmailMessageId = caseEmailMessage.id;
        emr.RelationId = UserInfo.getUserId(); // user id of the sender
        emr.RelationAddress = UserInfo.getUserEmail();
        emr.RelationType = 'FromAddress';
        insert emr; 
        system.debug('>>>>>=='+ emr );

    }
    else{

    }
}

} In simple words similiar like Email To case Feature ,not about creating records,but its about maintain the email loop one to one with same record/Case...

Please share your Inputs!!!..Please Let know if you need more info...

Reply Error:

I need to Reply to Email Meassage which I have Received for Particular Lead or Contact.Error comes up You cannot Perform this Action.How to customize the Reply and ReplyAll to attach custom Lightning Component Page. Reply & Reply All Error

I can see Delete Button Available for sent Emails,

Delete Button Available

Delete Button Not Available for Received Email,

Delete Button Not Available for Received Email

0

2 Answers 2

2

The EmailMessage record in your example is missing EmailMessageRelation information. Users can only reply/forward emails to EmailMessages they sent (EmailMessageRelation record with RelationType='FromAddress' and RelationId=userId) OR if they're a recipient on the EmailMessage (EmailMessageRelation record with RelationType='ToAddress', 'CcAddress' or 'BccAddress' and RelationId=userId).

Here's an example:

// Create EmailMessage record
EmailMessage emailMessage = new EmailMessage();
emailMessage.status = '3'; // email was sent
emailMessage.relatedToId = '006B0000003weZGIAY'; // related to record e.g. an opportunity
emailMessage.fromAddress = '[email protected]'; // from address
emailMessage.fromName = 'Dan Perkins'; // from name
emailMessage.subject = 'This is the Subject!'; // email subject
emailMessage.htmlBody = '<html><body><b>Hello</b></body></html>'; // email body
// Contact, Lead or User Ids of recipients
String[] toIds = new String[]{'003B000000AxcEjIAJ'}; 
emailMessage.toIds = toIds;
// additional recipients who don’t have a corresponding contact, lead or user id in the Salesforce org (optional)
emailMessage.toAddress = '[email protected], [email protected]';
insert emailMessage; // insert

// Add Email Message Relation for id of the sender
EmailMessageRelation emr = new EmailMessageRelation();
emr.emailMessageId = emailMessage.id;
emr.relationId = '005B0000003qHvOIAU'; // user id of the sender
emr.relationType = 'FromAddress';
insert emr;

See the following API docs:

5
  • Thank you, Austin!!! Really worked out for me.I will write a Blog Post with Detailed Information and I will post it here... Commented Jan 15, 2018 at 4:35
  • But when I click Reply & Reply all it giving me Error you cannot perform this action as Above attached Screenshot ... Commented Jan 15, 2018 at 9:35
  • I can see Delete Button for sent Emails, Not for Received Email...Attached Screenshots above... Commented Jan 15, 2018 at 11:58
  • I had Updated the Ticket with New Code I used ...@Austin Tam Commented Jan 23, 2018 at 4:02
  • I have Tried the above code in Multiple Dev orgs and Sanbox..Its working Fine..But The problem is I cannot Reply to Received Email in to salesforce as above attached screenshot and Tried the same in Multiple Dev orgs and Sanbox the problem continues...I have Raised a case to Salesforce support a week before,but Still no proper solution for this.. Commented Jan 26, 2018 at 4:03
0

Here you Go,

enter image description here Check This out here for Full Code:

send and Receive Email for standard and custom objects

Email Outbound Message Apex Class:

public class EmailServiceOutbound {
@AuraEnabled 
public static void sendMailMethod(String mMail ,String mSubject ,String mbody,string recid){
    system.debug('>>>>recordid>&&'+ recid);
    system.debug('>>main>>>'+mMail);
    system.debug('>>subject>>>'+mSubject);
    system.debug('>>body>>>'+mbody);
    //Inserting the record id in Email subject
    string subrec= '('+ recid +')';  
    // For storing Relation Id
    string opcid ='';
    //Email Sending Start
    List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();  
    //Create a new Email
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();        
    //Set list of people who should get the email        
    List<String> sendTo = mMail.split(',');
    //Setting Senders
    mail.setToAddresses(sendTo);        
    String addrUrl='replyemailtocontact@1xa8w2dg2mv8jwboee0zu8kf5yl5i45x4x2sy11h5871sme9vu.28-s3hgeay.ap6.apex.salesforce.com';

    // Set who the email is sent from
    mail.setReplyTo(addrUrl); // change it with your mail address.
    mail.setSenderDisplayName(UserInfo.getName() ); 
    system.debug('>>>>>=='+ UserInfo.getName() );   
    // Subject from Email Component and Record ID
    mail.setSubject(mSubject + subrec );
    //Setting Body from Email Component
    mail.setHtmlBody(mbody);        
    // Add your email to the master list
    mails.add(mail);        
    try {

        //Add Inbound Email Message for contact
        EmailMessage caseEmailMessage = new EmailMessage();
        caseEmailMessage.fromAddress= UserInfo.getUserEmail();
        caseEmailMessage.ToAddress = mMail;
        caseEmailMessage.FromName = UserInfo.getName();
        caseEmailMessage.Subject = mSubject;
        caseEmailMessage.HtmlBody = mbody;
        caseEmailMessage.Incoming= False;
        caseEmailMessage.TextBody = mbody;
        caseEmailMessage.status = '3';

        if(recid.startsWith('003')){
            caseEmailMessage.Contact__c = recid;
        }
        else if(recid.startsWith('00Q')){
            caseEmailMessage.Lead__c = recid;
        }
        else if(recid.startsWith('006')){
            caseEmailMessage.Opportunity__c = recid;
        }
        else if(recid.startsWith('0Q0')){
            caseEmailMessage.Quote__c = recid;
        }
        //For Custom Object
       /* else if(recid.startsWith('a1B')){
            caseEmailMessage.Reservation__c = recid;
        }*/
        insert caseEmailMessage;  

        system.debug('>>>>>=='+ caseEmailMessage ); 
        system.debug('>>>>>=='+ caseEmailMessage.Id );

         // Add Email Message Relation for id of the sender
        EmailMessageRelation emr = new EmailMessageRelation();
        emr.EmailMessageId = caseEmailMessage.id;
        emr.RelationAddress = UserInfo.getUserEmail();
        emr.RelationType = 'FromAddress';

        //Contact Email Message Relation Id
        if(recid.startsWith('003')){
             emr.RelationId = recid;
        }

        //Opportunity Email Message Relation Id
         else if(recid.startsWith('006')){
            List<OpportunityContactRole>pasid = [select id,ContactId,IsPrimary,OpportunityId,Role from OpportunityContactRole where OpportunityId=: recid];
            for (OpportunityContactRole opc : pasid ){
                opcid = opc.ContactId;
            }
            system.debug('#####'+ opcid);
            emr.RelationId = opcid;
        }

        //Lead Email Message Relation Id
        else if(recid.startsWith('00Q')){
             emr.RelationId = recid;
        }

        //Quote Email Message Relation Id
        else if(recid.startsWith('0Q0')){
            List<Quote>quoid = [select id,Name,ContactId from Quote where id =:recid LIMIT 1];
            for (Quote opc : quoid ){
                opcid = opc.ContactId;
            }
             emr.RelationId = opcid;
        }

      //Reservation Email Message Relation Id
        else if(recid.startsWith('a1B')){
             emr.RelationId = recid;
        }


    insert emr;     
        system.debug('>>>>>=='+ emr ); 
        system.debug('>>>>>=='+ emr.Id );

        // Send all emails in the master list
        Messaging.sendEmail(mails);
        system.debug('>>>>>=='+ mails);           

    }
    catch(Exception e){
        System.debug('Query Issue: ' + e);
    } 

}}

Email Inbound Message Apex Class:

global class EmailServiceInbound implements Messaging.InboundEmailHandler {

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    String myPlainText= '';
    // Add the email plain text into the local variable 
    myPlainText = email.plainTextBody;        
    system.debug('####unique message ID##'+email.messageId);

    // For storing Relation Id
    string oppcid ='';

    string sss= email.subject;
    System.debug('sss '+ sss);
    string [] a = sss.split('\\(');
    system.debug('a0 ='+ a[0]);
    //system.debug('a1 ='+ a[1]);
    string [] bb = a[1].split('\\)');
    system.debug('bb>>>Final ID>>>> '+bb[0] );
    string subrecid = bb[0] ;       

    If (subrecid.startsWith('003')){
        //Add Inbound Email Message for contact
        EmailMessage conEmailMessage = new EmailMessage();
        conEmailMessage.ToAddress =  String.join(email.toAddresses, ',');
        conEmailMessage.FromAddress = email.FromAddress;
        conEmailMessage.FromName = email.FromName;
        conEmailMessage.Subject = email.subject;
        conEmailMessage.status = '2';
        conEmailMessage.HtmlBody = email.htmlBody;
        System.debug('htmlBody:>>>> ' + email.htmlBody );
        conEmailMessage.Incoming= True;
        conEmailMessage.TextBody = email.plainTextBody;
        System.debug('TextBody:>>>>> ' + email.plainTextBody);
        conEmailMessage.Contact__c =subrecid;
        insert conEmailMessage;
        System.debug('Reply Email: ' + conEmailMessage ); 

        // Add Email Message Relation for id of the sender
        EmailMessageRelation emr = new EmailMessageRelation();
        emr.EmailMessageId = conEmailMessage.id;
        emr.RelationId = subrecid;// user id of the sender
        emr.RelationAddress = email.FromAddress;
        emr.RelationType = 'FromAddress';
        insert emr; 
        system.debug('>>>>>=='+ emr );
    }

    else if(subrecid.startsWith('00Q')) {
        //Add Inbound Email Message for Lead
        EmailMessage leadEmailMessage = new EmailMessage();
        leadEmailMessage.ToAddress =  String.join(email.toAddresses, ',');
        leadEmailMessage.FromAddress =  email.FromAddress;
        leadEmailMessage.FromName = email.FromName;
        leadEmailMessage.Subject = email.subject;
        leadEmailMessage.status = '2';
        leadEmailMessage.HtmlBody = email.htmlBody;
        System.debug('htmlBody:>>>> ' + email.htmlBody );
        leadEmailMessage.Incoming= True;
        leadEmailMessage.TextBody = email.plainTextBody;
        System.debug('TextBody:>>>>> ' + email.plainTextBody);
        leadEmailMessage.Lead__c = subrecid;
        insert leadEmailMessage;
        System.debug('Reply Email: ' + leadEmailMessage ); 

        // Add Email Message Relation for id of the sender
        EmailMessageRelation emr = new EmailMessageRelation();
        emr.EmailMessageId = leadEmailMessage.id;
        emr.RelationId = subrecid; 
        emr.RelationAddress = email.FromAddress;
        emr.RelationType = 'FromAddress';
        insert emr; 
        system.debug('>>>>>=='+ emr );
    }

     else if(subrecid.startsWith('001')) {
        //Add Inbound Email Message for Account
        EmailMessage accEmailMessage = new EmailMessage();
        accEmailMessage.ToAddress =  String.join(email.toAddresses, ',');
        accEmailMessage.FromAddress =  email.FromAddress;
        accEmailMessage.FromName = email.FromName;
        accEmailMessage.Subject = email.subject;
        accEmailMessage.status = '2';
        accEmailMessage.HtmlBody = email.htmlBody;
        System.debug('htmlBody:>>>> ' + email.htmlBody );
        accEmailMessage.Incoming= True;
        accEmailMessage.TextBody = email.plainTextBody;
        System.debug('TextBody:>>>>> ' + email.plainTextBody);
        accEmailMessage.Account__c = subrecid;
        insert accEmailMessage;
        System.debug('Reply Email: ' + accEmailMessage ); 

        // Add Email Message Relation for id of the sender
        EmailMessageRelation emr = new EmailMessageRelation();
        emr.EmailMessageId = accEmailMessage.id;
        emr.RelationAddress = email.FromAddress;
        emr.RelationType = 'FromAddress';
         List<Account>accid = [SELECT Id, (SELECT Contact.Id, Contact.Name,Contact.Email FROM AccountContactRelations) FROM Account where id =: subrecid LIMIT 1 ];
            for (Account acc:accid){
                for (AccountContactRelation actr : acc.AccountContactRelations ){
                    system.debug('act.Contact.Email = '+actr.Contact.Id);
                    oppcid = actr.Contact.Id;
                }
            }
        emr.RelationId = oppcid ;
        insert emr; 
        system.debug('>>>>>=='+ emr );
    }

    else if(subrecid.startsWith('006')){
        //Add Inbound Email Message for Opportunity
        EmailMessage oppEmailMessage = new EmailMessage();
        oppEmailMessage.ToAddress =  String.join(email.toAddresses, ',');
        oppEmailMessage.FromAddress =  email.FromAddress;
        oppEmailMessage.FromName = email.FromName;
        oppEmailMessage.Subject = email.subject;
        oppEmailMessage.status = '2';
        oppEmailMessage.HtmlBody = email.htmlBody;
        oppEmailMessage.Incoming= True;
        oppEmailMessage.TextBody = email.plainTextBody;
        oppEmailMessage.Opportunity__c = subrecid;
        insert oppEmailMessage;
        System.debug('Reply Email: ' + oppEmailMessage ); 

        // Add Email Message Relation for id of the sender
        EmailMessageRelation emr = new EmailMessageRelation();
        emr.EmailMessageId = oppEmailMessage.id;
        emr.RelationAddress = email.FromAddress;
        emr.RelationType = 'FromAddress';
        List<OpportunityContactRole>passid = [select id,ContactId,IsPrimary,OpportunityId,Role from OpportunityContactRole where OpportunityId=: subrecid];
        for (OpportunityContactRole opc : passid ){
            oppcid = opc.ContactId;
        }
        system.debug('#####'+ oppcid);
        emr.RelationId = oppcid;

        insert emr;  
        system.debug('>>>>>=='+ emr );           
    }

    else if(subrecid.startsWith('0Q0')){
        //Add Inbound Email Message for Quote
        EmailMessage quoEmailMessage = new EmailMessage();
        quoEmailMessage.ToAddress =  String.join(email.toAddresses, ',');
        quoEmailMessage.FromAddress =  email.FromAddress;
        quoEmailMessage.FromName = email.FromName;
        quoEmailMessage.Subject = email.subject;
        quoEmailMessage.status = '2';
        quoEmailMessage.HtmlBody = email.htmlBody;
        System.debug('htmlBody:>>>> ' + email.htmlBody );
        quoEmailMessage.Incoming= True;
        quoEmailMessage.TextBody = email.plainTextBody;
        System.debug('TextBody:>>>>> ' + email.plainTextBody);
        quoEmailMessage.Quote__c = subrecid;
        insert quoEmailMessage;
        System.debug('Reply Email: ' + quoEmailMessage );  

        // Add Email Message Relation for id of the sender
        EmailMessageRelation emr = new EmailMessageRelation();
        emr.EmailMessageId = quoEmailMessage.id;
        List<Quote>quoid = [select id,Name,ContactId from Quote where id =: subrecid LIMIT 1];
        for (Quote opc : quoid ){
            oppcid = opc.ContactId;
        }
        system.debug('#####'+ oppcid);
        if(oppcid !=null){
            emr.RelationId = oppcid;
        }
        emr.RelationAddress = email.FromAddress;
        emr.RelationType = 'FromAddress';
        insert emr; 
        system.debug('>>>>>=='+ emr );            
    }
    return result;
}}
1
  • 1
    Can you add relevant content from the link here? It's considered bad practice to just post a link to an external site as they have a habit of breaking over time making the answer useless.
    – Matt Lacey
    Commented Aug 6, 2018 at 1:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .