• Benjamin Ellington
  • NEWBIE
  • 0 Points
  • Member since 2015
  • Program Architect
  • Salesforce.com

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I'm not sure if I'm going about this the correct way, but I am trying to pull a list of lead email addresses with email domains that match the domains of contacts that are current clients.  The way I figured I'd go about this is by executing Anonymous Apex to send myself an email attachment.  The Anonymous Apex runs, but it hangs at "Unpacking results" in the Developer Console and at "Loading..." in the Workbench environment.  Am I going about this the wrong way?  I ran a similar query before and it worked great, but we have over 100k lead records so I am worried that it's just too much data.

Here's the code I am executing:

String finalList = 'Lead Email' + '\n';
Set<String> accountIds = new Set<String>();
Set<String> clientDomains = new Set<String>();
Set<String> leadEmails = new Set<String>();
List<Account> currentClientAccounts = [SELECT Id FROM Account WHERE Total_Won_Opportunities__c > 0];

for (Account a: currentClientAccounts){
     accountIds.add(a.Id);
}

List<Contact> currentClientContacts = [SELECT Id,Email_Domain__c FROM Contact WHERE AccountId IN :accountIds];

for (Contact c: currentClientContacts){
     clientDomains.add(c.Email_Domain__c);
}

List<Lead> leadList = [SELECT Email FROM Lead WHERE Email_Domain__c IN :clientDomains];

for (Lead leads: leadList){
     leadEmails.add(leads.Email);
}

for (String s: leadEmails){
     string line = s + '\n';
     finalList += line;
}

Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalList);
string csvname= 'LeadEmailsMatchingClientDomains.xls';
csvAttc.setFileName(csvname);
csvAttc.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new list<string> {'My Email Address'}; //this would be my actual email address in the real code
String subject = 'Lead Emails CSV';
email.setSubject(subject);
email.setToAddresses( toAddresses );
email.setPlainTextBody('Lead Emails CSV ');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});