I have built an apex class (below) that creates a custom object 'Messages' each time an email is sent in via the email service.

All works well except unfortunately the to address being saved is the email service address I have bcc'd on all emails - not the actual sender email.

I can't find any issues with the apex but obviously there must be another way to allocate the 'To Address'?

I would really appreciate any help at all :)

global class CreateMessageFromEmail implements Messaging.InboundEmailHandler {

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

    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

    sentiaforsales__Messages__c m = new sentiaforsales__Messages__c();
    m.sentiaforsales__Sender_First_Name__c = email.fromname.substring(0,email.fromname.indexOf(' '));
    m.sentiaforsales__Sender_Last_Name__c = email.fromname.substring(email.fromname.indexOf(' '));
    m.sentiaforsales__From_email__c = envelope.fromAddress;
    m.sentiaforsales__To_email__c = envelope.toAddress;
    m.sentiaforsales__Subject__c = email.subject;
    m.sentiaforsales__Body__c = email.plaintextbody;

    m.sentiaforsales__HTML_Body__c = email.HtmlBody;

    insert m;

    System.debug('====> Created contact '+contact.Id);

    return result;


  • Try email.toAddresses but bear in mind it returns a list of toAddresses. Refer to the documentation here - developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… Nov 28, 2018 at 3:48
  • Thanks.. I have added String listToAddress = ''; if (email.toAddresses != null) { for(String strTO: email.toAddresses) { listToAddress += strTO+' '; } } Nov 28, 2018 at 3:59
  • Gives me all to addresses. Just need to find a way in a flow now to split these up I guess as I want to allocate the messages to individual contacts with these to addresses Nov 28, 2018 at 3:59
  • well, if you store them in a comma-separated fashion you could directly pass that to the flow according to the documentation - developer.salesforce.com/docs/… Nov 28, 2018 at 4:36

1 Answer 1


You need to use the toAddresses from the InboundEmail Class. Try this -


but bear in mind it returns a list of toAddresses.

Refer to the documentation here - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_inbound_inbound.htm

You must log in to answer this question.

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