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
Lee_CampbellLee_Campbell 

Scheduled Email not working...

Hi folks,

 

I'm trying to create a scheduled outbound email. The class queries for all of the custom objects whose date fields are today and emails people whose email addresses are recorded as custom fields within the object. Only... it doesn't work. The code, and its schedule class, below do absolutely nothing.

 

public class EmailMessage
{  
   public static void SendEmail()
   {
       List<Milestone1_Project__c> activeproc = new List<Milestone1_Project__c>([Select id from
                                                                                 Milestone1_Project__c]);
       
       for( integer i=0;i<activeproc.size();i++){
       if(System.Today()==date.newinstance(activeproc[i].Date__c.year(),activeproc[i].Bid_Review__c.month(),activeproc[i].Date__c.day())){
       
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       String[] address = new String[]{activeproc[i].Owner.Email,activeproc[i].Legal_Contributor__c,activeproc[i].Technical_Specialist__c};
        mail.setToAddresses(address);
       
       for(OrgWideEmailAddress owa : [select id, Address from OrgWideEmailAddress]){
			mail.setOrgWideEmailAddressId(owa.id);
       }
 		
 
       mail.setSubject('Record of hours spent on Procurement: ' +activeproc[i].Name);
       mail.setBccSender(false);
       mail.setUseSignature(false);
       mail.setPlainTextBody('This is a test.');
       List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.Email[] { mail });
       System.debug('Email Sent: '+results.get(0).isSuccess() );
    }
   }
}
}

 And the Scheduler class:

 

global class ScheduleEnable implements Schedulable{
    global void execute (SchedulableContext SC){
        EmailMessage e = new EmailMessage();
    }
}

 Which I've then selected to run every week day at 08:00.

 

Does anyone see why this might not be working? I can't figure it out at all. It looks fairly solid to me, but I'm not certain about the String array. Am I barking up the right tree?

 

Any help you lovely folk of the Developer Force community could give would be much appreciated.

 

Thanks,

Lee

Best Answer chosen by Admin (Salesforce Developers) 
Lee_CampbellLee_Campbell

I think I may have figured this out... I'm not querying for any of the email addresses/date in my initial SOQL query at the beginning of the class. Rookie mistake. I'll be able to confirm whether this is the case when the scheduled job runs in five minutes' time. Hold on to your hats...

All Answers

kamlesh_chauhankamlesh_chauhan

You have only created object of EmailMessage class in schedule class.

 

Try below code.

 

 

global class ScheduleEnable implements Schedulable{
    global void execute (SchedulableContext SC){
        EmailMessage.SendEmail();
    }
}

 

Regards,

Kamlesh Chauhan, (Founder & CTO, LogicRain Technologies)

kamlesh@logicrain.com || http://www.logicrain.com || LinkedIn

 

Answers/Suggestions are my own.
If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

Lee_CampbellLee_Campbell

Hmmm... no difference that I can immediately see.

 

It would appear that I'm stuck in the "Schedulable class has jobs pending or in progress" stage, according to the Developer Console. Any ideas as to why this might be? Surely it hasn't taken four hours to search through a list of 10 objects (which is how many there are total), pick out the ones whose date fields match today (which is two of them) and email three people per object found (i.e. send six emails)!?

kamlesh_chauhankamlesh_chauhan

To apply the changes which I have mentioned, you need to remove the old scheduling then only it will allow you to make the changes to the scheduled class.

 

After applying the same, reschedule the class one more time.

 

Regards,

Kamlesh Chauhan, (Founder & CTO, LogicRain Technologies)

kamlesh@logicrain.com || http://www.logicrain.com || LinkedIn

 

Answers/Suggestions are my own.
If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

Jerun JoseJerun Jose

Hi,

 

As Kamlesh mentioned, you can only change your EmailMessage class after you remove all the scheduled jobs where it is currently used.

 

Anyway, I could not overlook the areas of improvement in your code, keeping in mind the governor limits.

 

public class EmailMessage{  
	public static void SendEmail(){
		List<Milestone1_Project__c> activeproc = new List<Milestone1_Project__c>([Select id from Milestone1_Project__c where Date__c = TODAY]);

		ID orgWideAddID = [select id, Address from OrgWideEmailAddress][0].ID;
		list<Messaging.SingleEmailMessage> mailList = new list<Messaging.SingleEmailMessage>();
		for(Milestone1_Project__c milProj : activeproc){
			Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
			String[] address = new String[]{milProj.Owner.Email, milProj.Legal_Contributor__c, milProj.Technical_Specialist__c};
			mail.setToAddresses(address);
			mail.setSubject('Record of hours spent on Procurement: ' +milProj.Name);
			mail.setBccSender(false);
			mail.setUseSignature(false);
			mail.setPlainTextBody('This is a test.');
			mailList.add(mail);
		}
		List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.Email[] { mail });
		System.debug('Email Sent: '+results.get(0).isSuccess() );
	}
}

 The above code is a more cleaned up version of the logic you had written.

 

To call this method, in the developer console, execute the code.

EmailMessage.SendEmail();

 To have this process scheduled, you can use the scheduled apex class given by Kamlesh.

Lee_CampbellLee_Campbell

Thanks guys.

 

I made everyone's suggested changes and still nothing, unfortunately. The Developer Console seems to think the class has been initiated, i.e. it's still giving me the "Schedulable class..." "problem", but none of the emails have landed. Could it be to do with my OWA being the email address that Salesforce generated for inbound handling (I used that because I want people to reply to this message and to extract some of the data therefrom).

 

Thanks,

Lee

kamlesh_chauhankamlesh_chauhan

Try to look at your current scheduled job and abort if anything is in progress.

 

Make one minor change to Jerun's code.

 

 

List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.Email[] { mailList });

If this doesn't helps, please attach snapshot of your developer console where you are seeting this error.

 

Regards,

Kamlesh Chauhan, (Founder & CTO, LogicRain Technologies)

kamlesh@logicrain.com || http://www.logicrain.com || LinkedIn

 

Answers/Suggestions are my own.
If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

Lee_CampbellLee_Campbell

Neither the line of code left in by Jerun or the correction you submitted work. Both give an error "Initial expression is of incorrect type, expected: Messaging.Email".

 

Also, if I look at my currently scheduled job in "Monitoring -> Scheduled Jobs" it just tells me when the job was submitted, by whom and when the next one's due. It doesn't tell me anything about the status of the job. Also, the job doesn't appear in any of the other "Monitoring" sub-sections. As an additional test, I requested an email log, and it's empty but for a couple of emails sent as part of something else I'm working on (which shares none of the same Apex, I should add).

 

Quite a conundrum. Thanks for your help so far though, folks. Any further ideas?

Jerun JoseJerun Jose

Chaning this.

 

List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.Email[] { mailList });

 

to

 

List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mailList });

should get you through the compile issues.

 

If the current class is not involved in any scheduled job, then you should be able to modify the class. Can you let me know what error you are facing now?

 

 

 

 

Lee_CampbellLee_Campbell

I'm still in the same boat...

 

Unfortunately, your code amendment suggestion didn't fix the compiling issue. When I revert to the old code which did compile, I'm still getting the error message on the developer console as described above, and the job itself only appears in the "Scheduled Jobs" portion of the "Monitoring" section - not in Apex Jobs or any other part of the "Monitoring" system. I still, for the life of me can't figure it out...

Tanvi SharmaTanvi Sharma

Hi,

 

Does anyone got this issue resolved?

 

Even I am facing the same problem.

Lee_CampbellLee_Campbell

I think I may have figured this out... I'm not querying for any of the email addresses/date in my initial SOQL query at the beginning of the class. Rookie mistake. I'll be able to confirm whether this is the case when the scheduled job runs in five minutes' time. Hold on to your hats...

This was selected as the best answer
Lee_CampbellLee_Campbell

Yep, that's what it was. Schoolboy error. It works fine now!

Tanvi SharmaTanvi Sharma

Thanks Lee. 

 

But I think there is some other problem occurring in my code below:

 

I am getting the same error - 'ErrorError: Compile Error: Initial expression is of incorrect type, expected: Messaging.SingleEmailMessage at line 109 column 62'

 

 

for(Opportunity opp: Trigger.new)
    {
        Opportunity oldoppty = Trigger.oldMap.get(opp.id);
        if(oldoppty.INTL_Status__c!=opp.INTL_Status__c){
            if(opp.SE_NO__c != null && opp.SE_NO__c != '' && (opp.INTL_Status__c != 'Open' || opp.INTL_Status__c != 'Rejected') && opp.EST_CHARGE_VOL__c >= 100000)
            {
                if(camp.get(opp.Id).contains('MOM_2_0') || camp.get(opp.Id).contains('MOM_1_2') || camp.get(opp.Id).contains('MOM_1_1') || camp.get(opp.Id).contains('MOM Pilot Campaign August 2010'))
                {
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                    // Strings to hold the email addresses to which you are sending the email.
                    String[] toAddresses = new String[] {'tanvi.sharma@aexp.com'}; 
                    String[] ccAddresses = new String[] {'tanvisha@in.ibm.com'};

                    // Assign the addresses for the To and CC lists to the mail object.     
                    mail.setToAddresses(toAddresses);
                    mail.setCcAddresses(ccAddresses);

                    // Specify the name used as the display name. 
                    mail.setSenderDisplayName('Salesforce Support');

                    // Specify the subject line for your email address.
                    mail.setSubject(opp.Name + 'has been Signed');

                    // Specify the text content of the email. 
                    mail.setPlainTextBody(opp.Name+ 'has agreed to accept the Card! The Opportunity in MerchantForce has been changed to a Status of Signed.'+
                    'Estimated Charge Volume: '+opp.EST_CHARGE_VOL__c +

                    'Signed by: ' +opp.Owner.Name +
                    'Sales Team: ' +opp.OWNER_SALES_TM__c +
                    'Campaign: ' +camp.get(opp.Id)+
                        
                    '---------------------------------------------------------------------------------------------------This is an automated notification sent by the MerchantForce CRM system. Please email MerchantForce Administrators in Lotus Notes to change the contents or be removed from this mailing.');

                    mail.setHtmlBody('<font face=Arial><b> ' + opp.Name +' </b> has agreed to accept the Card! The Opportunity in MerchantForce has been changed to a Status of Signed.<p>'+
                    'Estimated Charge Volume:  <b>' + opp.EST_CHARGE_VOL__c +'</b><p>'+
                    'Signed by:  <b>' +opp.Owner.Name +'</b><br>'+
                    'Sales Team: ' + opp.OWNER_SALES_TM__c + '<p>'+
                    'Campaign: ' +camp.get(opp.Id)+ '<p>'+
                    'Click <a href=https://cs12.salesforce.com/'+opp.Id+'>here </a> to view further details:<br></font><p><hr><font size=-1>'+
                    'This is an automated notification sent by the MerchantForce CRM system. Please email MerchantForce Administrators in Lotus Notes to change the contents or be removed from this mailing.</font>');

                    mailList.add(mail);
                }
                else if(camp.get(opp.Id).contains('2011 MOM Warming') || camp.get(opp.Id).contains('2011CD&MO') || camp.get(opp.Id).contains('MOM') || camp.get(opp.Id).contains('MOM Dupe') || camp.get(opp.Id).contains('2008ChannelDevelopment&Coverage') || camp.get(opp.Id).contains('2011MOMReview_Q4') || camp.get(opp.Id).contains('2011MOMReview') || camp.get(opp.Id).contains('2010CD&MO') || camp.get(opp.Id).contains('2009CD&MO') || camp.get(opp.Id).contains('CD&MO2010'))
                {
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                    // Strings to hold the email addresses to which you are sending the email.
                    String[] toAddresses = new String[] {'tanvi.sharma@aexp.com'}; 
                    String[] ccAddresses = new String[] {'tanvisha@in.ibm.com'};

                    // Assign the addresses for the To and CC lists to the mail object.     
                    mail.setToAddresses(toAddresses);
                    mail.setCcAddresses(ccAddresses);

                    // Specify the name used as the display name. 
                    mail.setSenderDisplayName('Salesforce Support');

                    // Specify the subject line for your email address.
                    mail.setSubject(opp.Name + 'has been Signed');

                    // Specify the text content of the email. 
                    mail.setPlainTextBody(opp.Name+ 'has agreed to accept the Card! The Opportunity in MerchantForce has been changed to a Status of Signed.'+
                    'Estimated Charge Volume: '+opp.EST_CHARGE_VOL__c +

                    'Signed by: ' +opp.Owner.Name +
                    'Sales Team: ' +opp.OWNER_SALES_TM__c +
                    'Campaign: ' +camp.get(opp.Id)+
                        
                    '---------------------------------------------------------------------------------------------------This is an automated notification sent by the MerchantForce CRM system. Please email MerchantForce Administrators in Lotus Notes to change the contents or be removed from this mailing.');

                    mail.setHtmlBody('<font face=Arial><b> ' + opp.Name +' </b> has agreed to accept the Card! The Opportunity in MerchantForce has been changed to a Status of Signed.<p>'+
                    'Estimated Charge Volume:  <b>' + opp.EST_CHARGE_VOL__c +'</b><p>'+
                    'Signed by:  <b>' +opp.Owner.Name +'</b><br>'+
                    'Sales Team: ' + opp.OWNER_SALES_TM__c + '<p>'+
                    'Campaign: ' +camp.get(opp.Id)+ '<p>'+
                    'Click <a href=https://cs12.salesforce.com/'+opp.Id+'>here </a> to view further details:<br></font><p><hr><font size=-1>'+
                    'This is an automated notification sent by the MerchantForce CRM system. Please email MerchantForce Administrators in Lotus Notes to change the contents or be removed from this mailing.</font>');

                    mailList.add(mail);
                }
            }
        }
    }

    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mailList });
Tanvi SharmaTanvi Sharma

I am getting the rror on my last lne of code i.e:

 

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mailList });

 

Any clues on this type of error??

Lee_CampbellLee_Campbell

I reverted to the code I originally posted, as I couldn't figure that {mailList} error out. However, to avoid the governor limits problem, I'm able to trim my list by a custom date field.