Email Address Set and Retrieve via Code in SuiteCRM

When interacting with Emails in SuiteCRM , it can be seen that they are stored differently than other Module field values. Email has a separate table along with Email Bean Relation middle table which relates Email Address to the corresponding Module Bean Record.

If you want to set, retrieve email address of a certain record, following code snippets might help.

Email Address class is located at include/SugarEmailAddress/SugarEmailAddress.php

$sea = new SugarEmailAddress;
Add a primary email address to Email Address table
$sea->addAddress($primaryemailaddress, true); 

Add an invalid email address
$sea->addAddress($primaryemailaddress, false, null, true); 

Add an email address that should be marked opt-out
$sea->addAddress($optemailaddress, false, null, false, true); 

Associate the email addresses with a given module record like Accounts or Contacts
$sea->save($record_id, "module_name");


If you want to retrieve primary email address for a module record, this can be achieved like:

$sea = new SugarEmailAddress; 

Grab the primary address for the given record represented by the $bean object
$primary = $sea->getPrimaryAddress($bean);  


And to grab all the email addresses associated with a record, we can do this.

$sea = new SugarEmailAddress; 

 Grab the array of addresses
$addresses = $sea->getAddressesByGUID($id, $module);
foreach ( $addresses as $address ) {
    echo $address->email_address . "\n";
}

One last thing about getting information based on email address. If you have email address of user and want to get the Bean or Record ID from that, their is a query which can be run to get the record associated with it.

 SELECT eabr.bean_id
                FROM email_addr_bean_rel eabr JOIN email_addresses ea
                    ON (ea.id = eabr.email_address_id)
                WHERE eabr.deleted=0 AND ea.email_address = 'foo@bar.com'

Comments