Pages

Tuesday, November 24, 2009

SugarCRM Customization: Custom Workflow E-mails

E-mail has become a popular tool for communication and for a number of purposes.

Within the scope of SugarCRM, the topic usually comes up in relation to the automation of some aspect of a business process, such as alerting a user when a record within the database has been assigned to them.  SugarCRM includes such a feature out of the box, but what if one wanted a bit more flexibility?

Suppose we encounter the following scenario:

Our deployment uses the Leads module to track and qualify potential customers.  Leads enter the system via two different ways: manual entry and web-to-lead.

Entries are required to have an e-mail address or they are not considered valid as our internal process use it for communications and other purposes.  Whenever a new lead is entered, it is automatically assigned to a specific user, who in turn receives an e-mail alerting them of the new record.  However, we want to expand this functionality to also automatically send a generic "Welcome/Thank You For Your Interest" message to the  Lead itself.

How do we go about accomplishing the above?

A simple technique that accomplishes the goal is the use of a logic hook.  (Check out my logic hook primer to learn the basics)

Through the use of a logic hook one can grab the e-mail address of the corresponding lead record and also create the message.  There are two additional techniques this approach teaches us:
  1. Sending of e-mail via the Sugar mailer engine
  2. Using the XTemplate engine to create the e-mail content
Here is the code that does our magic:
class Welcome {

function sendMessage(&$bean, $event, $arguments)

{
     require_once('include/SugarPHPMailer.php');
     $welcome_msg = new SugarPHPMailer();

     //Grab the Lead's Status (only send if Status = New)
     $status = $bean->status;

     //Set the TO name and e-mail address for the message
     $rcpt_name = $bean->first_name . ' ' . $bean->last_name;
     $rcpt_email = $bean->email1;

     //Set RCPT address
     $welcome_msg->AddAddress($rcpt_email, $rcpt_name);

     //Setup template
     require_once('XTemplate/xtpl.php');
     $xtpl = new XTemplate('custom/modules/Leads/WelcomeMessage.html');

     //Check the status on record
     if ($status == 'New')
     {
          //Send welcome msg to Lead
          $template_name = 'Lead';

          //Assign values to variables in template
          $xtpl->assign('EMAIL_ADDY', $rcpt_email);
          $xtpl->parse($template_name);

          $welcome_msg->Body = from_html(trim($xtpl->text($template_name))); 
          $welcome_msg->Subject = 'This is my test subject';
          $welcome_msg->prepForOutbound();
          $welcome_msg->setMailerForSystem();
          $welcome_msg->From = 'from_sample@example.com';
          $welcome_msg->FromName = 'Sample User';

          //Send the message, log if error occurs
          if (!$welcome_msg->Send())
          {
               $GLOBALS['log']->fatal('Error sending e-mail: ' . $welcome_msg->ErrorInfo);
          }
     }
 }

}

OK, that is the logic that creates and sends the message, but what about the actual content of the message?

That is contained in the WelcomeMessage.html file referenced in the above code.  Its content is included below:

<!-- BEGIN: Lead -->

Thank you for your inquiry and interest in our services.
{EMAIL_ADDY}
<!-- END: Lead -->

Notice that the template is rather simple, but clearly demonstrates how one is created and in turn, how one can merge SugarCRM data into it via the XTemplate engine.

31 comments:

  1. Hi Angel,
    I've been looking for how to attach files in an email template alert of workflow but I've not found anything about it.

    Could you help me with that?

    I need to send an email using workflow, and that email have to include an attached file.

    Thanks in advance

    ReplyDelete
  2. Take a look at the SugarPHPMailer.php file in the include directory.

    I've never tried it myself, but it seems like the handleAttachments() function in there will address your needs.

    ReplyDelete
  3. Thanks Angel,

    I've been working in other projects and I left it by a few days.
    If I find the solution, I'll post it here.

    Regards

    ReplyDelete
  4. Cool. Thanks in advance for sharing.

    ReplyDelete
  5. Hi Angel, first of all thanks for your shearings.

    Do you happend to know how to trigger a specific logic hook of Sugar from outside Sugar. I mean, I have a custom webpage for customers where I want them to fill some information (lest say update contact information) then I need to load that to the specific record in SugarCRM (easy to do with direct access to the DB) and I need the trigger the logic hook if necessary, this is not possible if I use a direct access to the DB.

    Thanks in advance for your help!

    ReplyDelete
  6. Hi Angel, I have some problems trying to trigger a logic hook from outside sugar.

    I have a custom web-page where some contacts can update informeation of a custom module. I can save the information using direct access to the DB but this is not useful if I need to trigger the logic hook depending on the data.

    Any ideas? Thanks in advance!

    ReplyDelete
  7. If you are manipulating the system via external scripts, why not include the logic hook code in your external script? Not sure I understand why it has to run via the logic hook given that you are already performing actions outside that context.

    Alternatively, your external script can also be used to create the Sugar objects using the corresponding Sugar class files. Records created via that process should trigger your logic hook.

    ReplyDelete
  8. thanks for your answer!

    I was working arround this and I realized that I need to connect to sugar via SOAP with my php web page. That should make it all nice and easy.

    The thing is, I cant connect, I'm trying with nusoap.php but it's not working, I have an LDAP authentication in sugar.

    I'm trying this:
    http://web.archive.org/web/20071028163448/http://www.sugarcrm.com/wiki/index.php?title=Authenticate_with_LDAP_through_SOAP

    Did you ever do something like this in php?? I would be of great help, plus we can do wonderfull if we connect via SOAP.

    Cheers!

    ReplyDelete
  9. I am working on a similar logic hook for the Tasks module. How to I get the Task Creator's email address?
    Thanks

    ReplyDelete
  10. @Phe
    Sorry for delay. Not sure how I missed your comment.

    Try using:

    global $current_user;
    $current_user->email1;

    If that doesn't work, use the ID value in $bean->created_by to query the email_addresses table and retrieve it.

    ReplyDelete
  11. What about secondary email addresses? How would one grab a secondary email address to send to as opposed to the primary?

    ReplyDelete
  12. @Greg:

    Try using $current_user->email2 as that is the normal convention for similar scenarios relating to Contacts and Leads, etc.

    ReplyDelete
  13. I'll give that a shot -- thanks Angel!

    ReplyDelete
  14. Hi Angel

    How would I be able to include HTML tags into the email template?

    Andre
    UpShoot Media

    ReplyDelete
  15. @Andre:

    Take a look at this other post:
    http://cheleguanaco.blogspot.com/2011/06/sugarcrm-customization-workflow-emails.html

    It expands on this idea, to utilize the email template system built into Sugar itself. Through it you could create your plain text or HTML template.

    ReplyDelete
  16. When creating an HTML-formatted mail, I'm seeing a lot of the inbound mails go to junk/spam.

    In the sendMessage function, I did the following
    $welcome_msg->IsHTML(true); //set FORMAT to HTML
    (by default IsHTML is false, for plain-text sending).

    The email needs to contain a hyperlink, which is why I felt it necessary to send the mail as HTML. The mail comes in with the hyperlink fully-formed, but
    many times the mail gets routed as spam.

    Any ideas? Thanks,
    Adam

    ReplyDelete
  17. @AdamTell

    No, unfortunately I don't really have any suggestions. The reasons for a message being classified as spam can vary greatly and isn't always tied to it being/not being HTML.

    ReplyDelete
  18. Hey Angel, great posts and blog. I was wondering if you have any thoughts on the sending of multiple emails using an email template with merged fields? As an example, I need to send an email to 10 contacts, not enough for a Campaign and too many to do manually. I have created an email template, selected the contacts and selected the Email menu option. I select my Template from the pop up email window and send the email.

    The individual merge fields e.g. first name DO NOT merge for all contacts the email is sent to. It ONLY appears to merge for the first name in the list of people the email is sent to, either in the To, CC or BCC fields. Do you have any idea how I could customise/fix this behaviour so that it would merge with ALL email recipients?

    Thanks for any leads you can give me

    Marty Peet

    ReplyDelete
    Replies
    1. Hi Marty, thanks for your feedback. Happy to hear it.

      Campaigns is really the best tool to handle that scenario, even if it is only a few records. Another possibility would be to use code similar to that in this post and use the parse option in SugarPHPMailer (I believe) to merge the info.

      Modifying the email client in general is not something for the faint of heart, so I wouldn't recommend going that route.

      Delete
  19. Hello Angel,

    I have some configuration about sending invites in meeting. I want to use the email template in sending invites. Is that possible? Where should i go to customize? Thank you so much. :)

    ReplyDelete
    Replies
    1. Unfortunately I've never modified that part of Sugar, so I couldn't tell you if it is possible to do that in an upgrade safe manner or how to do it otherwise.

      Delete
  20. hello angel
    i want to know, is that logic hook helps in sending email notification to client on case logged??

    ReplyDelete
    Replies
    1. Swapna,

      You can certainly apply it to the Cases module. It just a matter of defining the hook within /custom/modules/Cases/logic_hooks.php and providing the supporting class file similar to the one in this example.

      Of course, you would also want to customize it to introduce your logic that determines when the email should go out.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. hello angel
      i have already created logic_hooks.php by referring you blog.
      but i still don't understand some of things in code. i am copying my logic hook file here and one other file too. can you tel me what do i need to change the code now? is their something i am missing in code? i am completely new to this.
      thanks in advance.

      -------LOGIC_HOOKS.PHP-----------



      ------------EMAIL_NOTIFICATION.PHP---------

      status;

      $email_msg->Subject = 'Case : ' . $bean->name;
      $email_msg->prepForbound();
      $email_msg->setMailerForSystem();
      $email_msg->Body = $bean->description;
      $email_msg->From = $admin->settings['info@companyname.com'];
      $email_msg->FromName =$admin->settings['companyname'];

      $email_msg->AddAdress('EMAIL_ADDRESS');

      if (!$email_msg->Send())
      {
      $GLOBALS['log']->fatal('Error sending e-mail: ' . $welcome_msg->ErrorInfo);
      }
      }

      }
      }

      ?>

      Delete
  21. hi
    is it possible to get notification mail when tasks in cases are completed???

    ReplyDelete
    Replies
    1. Sure, it would just be a variation of the example in this post, except it would be triggered via a logic hook on the Tasks module which would in turn confirm that the task is set to "completed" and associated with a case.

      Delete
  22. Hi! You always know a good blog post when it's still relevant 5 years later ;)

    I have a custom module (client deliverable) which has a many-to-one relationship with another custom module (photo shoot) which has a many-to-one relationship with Accounts.

    I want Sugar to automatically send an email to the Account address when a deliverable is created. Also I want to refer to fields in the deliverable and the photo shoot (i.e. two custom modules) in this email.

    Do you know if that can be done? Any pointers?

    Thanks!

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Hey angel. I want to send emails to users everyday using cron. So, my question is can i add above code in my cron.php file and set up cron job or I have to do something for that. Please guide me soon on that. Thank you.

    ReplyDelete

Your comments, feedback and suggestions are welcome, but please refrain from using offensive language and/or berating others. Thank you in advance.