Mailing with Joomla’s JMail

I just finished implementing a cron job script that will email all people who’s the target of an activity in JomSocial’s activity stream.

So without further ado, here is an example of how to use JMail in a standalone fashion (explanations below the listing):

function sendActivityEmails(){
	$sql = "SELECT DISTINCT u.*, a.*, AS actor_name, AS act_id 
			FROM jos_users u, jos_users u_actor, jos_community_activities a, jos_community_fields_values fv
			WHERE = AND = AND !=
			AND fv.user_id = AND fv.field_id = 21 AND fv.value = 'Yes' 
			AND a.email_sent = 0 GROUP BY";
	$rows = $this->loadObjectList($sql);
                $mail = JFactory::getMailer(); 
		foreach($rows as $row){
                        $mail->to = array();
		        $conf =& JFactory::getConfig();
			$body = str_replace('{target}', 'you', $row->title);
			$body = str_replace('{actor}', ucfirst($row->actor_name), $body);
			$mail->setSubject("Paceville activity update");
			if($conf->getValue('config.mailer') == 'smtp'){
			if($mail->Send() === true)
				$this->exec("UPDATE jos_community_activities SET email_sent = 1 WHERE id = ".$row->act_id);

1.) First of all we need an SQL string that will fetch the actor and target user of the activity, but only if the target has enabled email updates and the activity in question hasn’t triggered an email to be sent already.

2.) If we get any rows we will start looping through them, we will replace {actor} and {target} with the name of the actor and you when it comes to the target. Important, note the $mail->to assignment there during each loop, if we didn’t do that recipients would build up in a cumulative fashion resulting in too many mails going out to too many people who are not the intended recipients.

3.) We set the body with the string we prepared in #1. When it comes to sender we will use a string set in the global configuration in Joomla. The recipient will be the email of the target user.

4.) If smtp has been set as the mailing technique in the Joomla backend we use it, otherwise the PHP mailer will be used, note that the sendmail option is not given any consideration in the above example.

5.) If the Send() method returns exactly (===) true (remember that == will return true for anything except false and 0) we will update the activity’s email_sent column to true so we don’t send another email again for the same activity. If the Send() method fails it will return an error object.

Related Posts

Tags: , ,