More Email Maniuplation with Code

sugarcrmdevelopers —  October 13, 2011

Some time ago, John Mertic (SugarCRM Community Manager and ace developer) posted up a nice tutorial on retrieving and using email addresses within Sugar via PHP. I’ve found that posting pretty helpful, but I needed to go a few more steps for a recent project.

For my project, I need to copy any and all existing email addresses from a given Lead to a new Contact. The code, though, will work with any two records, even if they’re beans of the same module. Here’re the guts:

 // assume $bean is already defined as an existing Lead record.
$contact=new Contact;
$contact->save(); // provides an ID for the new record
foreach ( $bean->emailAddress->addresses as $address ) {
    $contact->emailAddress->addAddress($address['email_address'], $address['primary_address'], $address['reply_to_address'], $address['invalid_email'], $address['opt_out']);

Here’s a quick “gotcha” worth noting, though. If you are attempting to do this in a logic hook, possibly before_save or after_save, you’re may experience your record receiving the email address relationships, and then having the relationships deleted out from under it. To prevent this, ensure that saving the email addresses is the last operation you perform on the new record bean. Subsequent saves ($contact->save()) will probably invoke SugarEmailAddress::handleLegacySave(), which looks in $_REQUEST for email address widgets and will fail to find what it’s really looking for for the Contact.