+ Start a Discussion
LakshmiGenLakshmiGen 

How to send remainder Mails using apex code

Hi,

 

I need to send Remainder mails to users based on specific period of time using apex ccode.Could you please help me on this. As i am new to this sales force idont have idea.

 

Please share sample code or links which will be useful to complete my Task.

 

 

Regards

Lakshmi Prasanna.

kirkevonphillykirkevonphilly

I've done this in the past by creating a custom "Reminder" object and utilizing a scheduled Apex class.  Within the class, I had a query that looked at records in my Reminder object to gather up recipients of the "reminders."  It did so by using a "Next Reminder Date," returning the records where that date was today().  

 

The class then worked with the results to send out the email.  After sending the email, it either cleaned up helper object records that no longer needed reminders or scheduled the next reminder.

 

The schedulable Apex class was scheduled to run every day at a specific time.

 

 

Vadim RudkovVadim Rudkov

I don't think you necessarily need to use apex code for this purpose. Maybe you will succeed with workflow rules and email alerts. Have a look at https://na1.salesforce.com/help/doc/en/salesforce_workflow_cheatsheet.pdf

Michael_TorchedloMichael_Torchedlo

As the other commenters have said, there is more than one solution for this, so it depends on your use case.  Please describe in more detail what kind of reminder you are trying to produce?

 

For example:

Suppose you want to send a reminder email any time a user creates an opportunity and forgets to add products.  You can do this with a regular workflow rule and email notification.  Any opportunity meeting the conditions generates its own email alert.

 

However, suppose you also want to send a different type of reminder once a month for certain opportunities that are outdated.  Instead of sending out one email for each opportunity (and having one user get 50 emails at once), you prefer for each user to get only one email, which lists all of the opportunities for that person.  This can be done using an Apex class.  It would involve a query and a dynamic number of opportunites each time, so it requires more coding than a regular workflow email.

 

Apex developer guide: sending outbound emails.

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound.htm

LakshmiGenLakshmiGen

Hi  kirkevonphilly,

LakshmiGenLakshmiGen

Hi Michael_Torche,

 

 

 we send first notification mail to user in order to approve the case.If he doesnt respond to the mail, we will send remainder one at specific period of time based on configuration in the object.

If  still the Approver doent respond then we send second remainder after  that escalation mail.

Now i need the apex code and scheduler code to trigger these interval mails to users based on query.

Could you please provide me the sample code. It will be helpfull.

 

Regards,

Lakshmi Prasanna

Michael_TorchedloMichael_Torchedlo

Lakshmi,

 

Since these emails are part of your Approval process, what you're describing sounds very much like you should be able to use just regular Workflow Emails, and not need apex code, like v.rudkov originally suggested.  You can set a workflow rule to run that meets a certain condition, and then uses time triggers to send one email immediately, a 2nd email after 24 hours, a 3rd email after 72 hours, and so on.  If at any point, the user DOES approve the case, or makes the changes you request, then the workflow criteria will no longer be true, and so the later reminders will be cancelled.

 

http://na1.salesforce.com/help/doc/en/creating_workflow_alerts.htm

 

Personally, I would not try to implement this using Apex code.  An Apex class with a schedulable interface can create a program that will run once a day or once a week, but it will not be running sepearate triggers on separate timelines for each case.  The better way to do that is using workflow emails.

 

Excerpts from a knowlege article:

https://help.salesforce.com/HTViewSolution?id=000005245&language=en_US

 

Can I configure multiple actions to occur at different points in time for the same rule?
Yes, you can create a time line of actions by configuring multiple time triggers and defining actions for each one.

For example, consider a rule for all high value opportunities (value > $500K, probability > 70%). The immediate actions could include sending an email alert to the account team stating that a new high value opportunity has been created. The time-dependent actions could include the following:

  • 10 days before the opportunity, close date, assign a task to the opportunity owner to follow up with the customer.
  • 7 days before opportunity close date, change the owner of the opportunity to VP Sales, and send an email alert to the new owner.

 

Will the pending actions in the queue ALWAYS fire?
No. Time-dependent actions remain in the workflow queue only as long as the rule criteria for the workflow rule is still valid. If a record no longer matches the rule criteria, Salesforce removes the time-dependent actions queued for that record.

For example, an opportunity workflow rule may specify:

  • A criteria set to "Opportunity: Status not equals to Closed Won, Closed Lost."
  • An associated time-dependent action with a time trigger set to seven days before the opportunity close date. If a record that matches the criteria is created on July 1st and the Close Date is set to July 30th, the time-dependent action is scheduled for July 23rd. However, if the opportunity is set to "Closed Won" or "Closed Lost" before July 23rd, the time-dependent action is automatically removed from the queue.

 

 

Because you asked for an example of Apex code sending out emails, here is one, but I strongly recommend that you do not use this for your project.  The example uses 2 classes - one to do the work, and the other to be the schedulable interface (plus a a testing class in addition).  The schedulable interface is what will allow you to schedule the program to run at a regular interval.  For example, if you set it to run once a day, then each day it will query to find if any cases need reminders to be sent and it will send them all in one batch, at the same time. 

 

global class ScheduleOldOpportunityReminder implements Schedulable{   
    global void execute(SchedulableContext sc){      
        OldOppReminder Z = new OldOppReminder();   
    }
}

 

 

global class OldOppReminder {

public List<Case> OldOpps;

public OldOppReminder(){
   OldOpps = this.FindOpps();
   if(OldOpps.size()>0){
      List<Messaging.SingleEmailMessage>  myEmails = new List<Messaging.SingleEmailMessage>();
      this.WriteSendEmail(OldOpps, myEmails);
      Messaging.sendEmail(myEmails);
   }   
   OldOpps.clear();
   }

public List<Case> FindOpps() {
   // query to find only the cases that match your conditions requiring email alerts to be sent
   oldopps=[SELECT .... FROM CASE WHERE ...];
   return OldOpps;
   }

public void WriteSendEmail(List<Case> FlaggedOpps, List<Messaging.SingleEmailMessage> myEList) {
   //this method creates all the emails, but does not send them
   //this example would email the case owner

   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String mbody = '';
   User ToRep = FlaggedOpps[0].Owner;
   for(Integer k=0; k<FlaggedOpps.size();k++){
         ToRep = FlaggedOpps[k].Owner;
         mail = new Messaging.SingleEmailMessage();            
         String[] toAdd = new String[] {ToRep.Email};
         mail.setToAddresses(toAdd);
         mail.setUseSignature(FALSE);
         mail.setSubject('Reminder: case overdue');
         mBody = 'the body of your email reminder';
         mail.setPlainTextBody(mBody);
         myEList.add(mail);
      }
   }
}

 

 

BhavanaBhavana
Hi 
Can you please help in using above code to send approval reminder email to pending approver on Opportunity. I have found below query to get the current pending approver name.

SELECT CompletedDate, ElapsedTimeInDays, ElapsedTimeInHours, ElapsedTimeInMinutes, Id, ProcessDefinitionId, Status, SubmittedById, TargetObjectId FROM ProcessInstance WHERE TargetObjectId = 'aaaaaaaa' And Status ='Pending'

SELECT ActorId,Comments,CreatedById,CreatedDate, ElapsedTimeInDays, ElapsedTimeInHours,   ElapsedTimeInMinutes,Id, OriginalActorId, ProcessInstanceId,  StepNodeId,StepStatus, SystemModstamp FROM ProcessInstanceStep where ProcessInstanceId='bbbbbbb'

Thanks.