How can i user sugar email system on php jobs?

I am creating a scheduler job that needs to send e-mails to users and contacts and create tasks to users. How can i do that via php code? I think i have a idea of how to create tasks through new Bean but i don't have a clue on how to send e-mails from sugar.

Here is what i got so far:

function lftm_it_data_ativacao_job() {
    
    
     $sql = "SELECT T0.id, T1.lftm_it_acima_max_c, T1.lftm_tipo_atendimento_c, T1.lftm_carteira_adm_c T1.lftm_dias_saldo_positivo_c, ";
     $sql .= "T0.email FROM contacts T0 ";
     $sql .= "INNER JOIN contacts_cstm T1 ON T0.id = T1.id_c ";
     $sql .= "WHERE T1.lftm_it_acima_min_c = 1;";
    
    
     $GLOBALS['log']->fatal('Start positive cash job');
     $cnt = 0;
     $conn = $GLOBALS['db']->getConnection();
    
     $GLOBALS['log']->fatal('Got Connection');
    
     $stmt = $conn->executeQuery($sql);
    
     $GLOBALS['log']->fatal('Query executed');
    
     while($row = $stmt->fetch()) {    
    
         
          if($row['lftm_carteira_adm_c'] = 1) {
              
          } else {
               if($row['lftm_tipo_atendimento_c'] = 'SelfService') {
                    if($row['lftm_dias_saldo_positivo_c'] == 3) {
                         //send email to client
                    }
                    if($row['lftm_dias_saldo_positivo_c'] >= 10) {
                         //create task to advisor
                    }
               }
               if($row['lftm_tipo_atendimento_c'] = 'Regular' || $row['lftm_tipo_atendimento_c'] = 'FullService') {
                    if($row['lftm_it_acima_max_c'] != 0) {
                         if($row['lftm_dias_saldo_positivo_c'] == 1) {
                              //send email to advisor and client informing the need to allocate cash
                         }
                         if($row['lftm_dias_saldo_positivo_c'] == 4) {
                              //create task to officer to reach advisor
                         }
                         if($row['lftm_dias_saldo_positivo_c'] >= 10) {
                              //send email to advisor and superior informing that cash didn't change
                         }    
                    } else {
                         if($row['lftm_dias_saldo_positivo_c'] == 1) {
                              //send email to officer and client with order to allocate cash
                         }
                         if($row['lftm_dias_saldo_positivo_c'] == 3) {
                              //create task to officer to reach client
                         }
                         if($row['lftm_dias_saldo_positivo_c'] >= 10) {
                              //create task to advisor informing that officer didn't get response
                         }    
                    }
               }
          }
          $cnt++;
          $GLOBALS['log']->fatal(''. $cnt .' Registers Saved');
     }
    
     $GLOBALS['log']->fatal('All Registers Saved');
    return true;

}
  • Ciao Giovanni, 

    If you have Enterprise or Ultimate, look into Advanced Workflow, it may greatly simplify your life.

    If you are on Professional, like me, then you'll need to work with logic hooks to create your own workflow.

    I use the two functions below to send emails either individually (the same email to multiple addresses, one per address) or send one email to multiple recipients in the To or Cc fields.

    I suggest you put these in a custom Utilities folder so that you can reuse them across your application, then include them where needed and call the function. This will help with code maintenance and you'll be able to update your functions in one place for the whole application when needed. It will also make your code more readable.

    Please note that I believe there will be better ways of doing this with the upcoming changes in the Emails module  in 7.10/7.11 for on demand and in version 8.0 when that comes out in the spring for on-site customers. 

    The parameters:

    ToEmailAdd is an array or semicolon delimited list of email addresses

    FromEmailAdd is a single email Address that the email will come from

    FromEmailName is the name you want to see next to the From Address

    EmailSubject is just that

    EmailBody is the html body of the email

    In the second function I added CCEmailAdd for the email addresses to be included in the CC.

    <?php
      //Function to send Email message
      //one email per recipient

    function sendEmail($ToEmailAdd, $FromEmailAdd, $FromEmailName, $EmailSubject, $EmailBody) {
      global $sugar_config;
      $GLOBALS['log']->debug('PREPARE EMAIL to ' . print_r($ToEmailAdd, true));
      require_once ('modules/Emails/Email.php');
      if(is_array($ToEmailAdd)){
        $To = $ToEmailAdd;
      }else{
        $To = explode(';',$ToEmailAdd);
      }
      foreach ($To as $to_addr){
        $GLOBALS['log']->debug('PREPARE EMAIL TO:' . $to_addr);
        if (filter_var($to_addr, FILTER_VALIDATE_EMAIL)){
          try{
            $phpMailer = MailerFactory::getSystemDefaultMailer();
            $mailTransmissionProtocol = $phpMailer->getMailTransmissionProtocol();
            $FromEmailIdentity = new EmailIdentity($FromEmailAdd, $FromEmailName);
            $header_array = array(
              'From'=>$FromEmailIdentity,
              'ReplyTo'=>'',
              'Sender'=>$FromEmailIdentity, //mandatory
              'Subject'=>$EmailSubject,
            );
            $phpMailer->constructHeaders($header_array);
            $phpMailer->addRecipientsTo(new EmailIdentity($to_addr, $to_addr));
            $phpMailer->setHtmlBody($EmailBody);
            $phpMailer->send();
          }catch(MailerException $me) {
            $message = $me->getMessage();
            $GLOBALS["log"]->warn(
              "SendGroupEmail: error sending e-mail (method: {$mailTransmissionProtocol}), (error: {$message})"
            );
          }
        }
      }
      return;
    }
    ?>
    <?php
      //Function to send one Email message to multiple recipients

    function sendGroupEmail($ToEmailAdd, $FromEmailAdd, $FromEmailName, $EmailSubject, $EmailBody, $CcEmailAdd = array()) {
      include_once('modules/Mailer/MailerFactory.php');
      global $sugar_config;
      $To = array();
      $Cc = array();

      if(is_array($ToEmailAdd)){
        $To = $ToEmailAdd;
      }else{
        $To = explode(';',$ToEmailAdd);
      }

      if(is_array($CcEmailAdd)){
        $Cc = $CcEmailAdd;
      }else{
        $Cc = explode(';',$CcEmailAdd);
      }
      try{
        $phpMailer = MailerFactory::getSystemDefaultMailer();
        $mailTransmissionProtocol = $phpMailer->getMailTransmissionProtocol();
        $FromEmailIdentity = new EmailIdentity($FromEmailAdd, $FromEmailName);
        $headers = new EmailHeaders();
        $header_array = array(
          'From'=>$FromEmailIdentity,
          'ReplyTo'=>'',
          'Sender'=>$FromEmailIdentity, //mandatory
          'Subject'=>$EmailSubject,
        );
        $headers->buildFromArray($header_array);
        $phpMailer->setHeaders($headers);
        //$phpMailer->setHtmlBody($EmailBody);
        $phpMailer->setTextBody($EmailBody);

        foreach($To as $to_addr){
          //note should be new EmailIdentity(<email_address>, <name>)
          //we don't have a name for these
          $phpMailer->addRecipientsTo(new EmailIdentity($to_addr, $to_addr));
        }
        foreach($Cc as $cc_addr){
          //note should be new EmailIdentity(<email_address>, <name>)
          //we don't have a name for these
          $phpMailer->addRecipientsCc(new EmailIdentity($cc_addr, $cc_addr));
        }
        $phpMailer->send();
      }catch(MailerException $me) {
        $message = $me->getMessage();
        $GLOBALS["log"]->warn(
          "SendGroupEmail: error sending e-mail (method: {$mailTransmissionProtocol}), (error: {$message})"
        );
      }
      return;
    }
    ?>

    One more thing, try to use SugarQuery instead of SQL, or you will have to redo all your SQL to abide by the prepared statements requirements:

    Use of prepared statements in Sugar 7.9 « Sugar Developer Blog – SugarCRM 

    Hope this helps,
    FrancescaS

  • I really tried using SugarQuery on previous schedulers i made (as you sugested on previous posts) but the only ones that worked for me were the ones that i used SQL. SQL runs extremely more fast in my experience as well. I do use Enterprise but my company assign clients to two employees at the same time and advanced workflow only let me choose 1 assign user or his superior to create new records. I'll try using logic hooks as you showed. Thanks for the huge help. 

  • Is there any way to execute a advanced workflow within a scheduler?

  • I don't know, I work on PRO and have never worked with Workflow.
    You may want to ask this as a separate question so someone else may have a chance to answer it.

    FrancescaS

  • Where the variables you send to the function come from? Is this a Scheduler?

  • This is not a scheduler, it's just a utility function that you can call from wherever you need to call it, I use it primarily from schedulers but I also call it from within a logic_hook if needed.

    You will build the parameters as needed from your Scheduler or logic hook.

    Say that you have a logic_hook to notify the assigned user when a new email comes in on a case that they are assigned to. I'm not including the full logic hook, this is just an example for the parameters.

    //include the send_email.php that you store in your Utilities folder
    include_once('custom/Utils/send_email.php');
    global $sugar_config;
    //get the $email bean for the newly created email
    $email = ...
    // get the $case bean for the case it's related to
    $case = ...
    //get the assigned user's email address

        $u = BeanFactory::retrieveBean('Users', $case->assigned_user_id);
        $user_email = $u->emailAddress->getPrimaryAddress($u);
    // set up your message

    $emailBody=<<<BODY
    New email received on [CASE:{$case->case_number}] $case->name<br>
    Current Case Status: $case->status<br>
    Assigned to: $u->user_name<br>
    From: {$email->from_addr_name} ( {$email->from_addr} )<br>
    To: {$email->to_addrs}<br>
    Cc: {$email->cc_addrs}<br>
    Subject: $email->name<br>
    See: {$sugar_config['site_url']}/#Cases/{$case->id}
    <br>
    BODY;
    $to_address = $user_email;
    //set up your subject line
    $subject = "New Correspondence on Case [CASE:{$case->case_number}] $case->name";
    //set up your From name and address
    $from = 'SugarCRM Case Update';
    $from_address = 'myaddress@mycompany.com';
    sendEmail($to_address, $from_address , $from, $subject, $emailBody);

     

     

  • Wow. I didn't know i could use other jobs inside jobs. Thanks for the insight!

  • I know i just thought for security reasons sugar woudn't let us use.