Thursday, December 23

Mailing with Joomla: HTML and Text

Joomla has its own built in version of PHPMailer called JMail. Hey, we set all these email configurations in the setup, might as well use those.

$mail =& JFactory::getMailer();
$config =& JFactory::getConfig(); //this is where we grab info from the config file
$mail->useSMTP(
$config->getValue('config.smtpauth'),
$config->getValue('config.smtphost'),
$config->getValue('config.smtpuser'),
$config->getValue('config.smtppass')
);
Now we can define more stuff for useSMTP, but unless your server settings aren't standard, you don't really need to. But it's all in the config file too, easy way to see it all is just to print_r($config).

Now, I want to send this email as html because it looks nicer, but I have to make sure to set a text only one for those people reading the emails on their phones, etc.
$HTMLmsg = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Message title</title>
</head>
<body>
<p>Here is some text. It looks nice.</p>
</body></html>';
$textmsg = "Here is some text. It looks ok.";
$mail->setBody(&HTMLmsg);
$mail->isHTML(true);
$mail->AltBody=&textmsg;
AltBody is a variable, not a function. It was carried over from PHPMailer. Setting this automatically sets the email to multipart/alternative. It is read by clients that don't have HTML email (like my phone), but clients that can read HTML will see the normal body.

Notice I used double quotes on $textmsg. This is in case I want to use newlines, php will escape them (I mentioned this earlier).

We're almost done. Just need a recipient, sender and subject. We can use another Joomla config value to set who the email is sent from.
$mail->addRecipient('example@example.com');
$mail->setSender($config->getValue('config.mailfrom'));
$mail->setSubject('Test email');
Well this seems good right? I spent a few minutes with this all set up, testing, but no email was sent. Oh yeah, forgot one very important line.
$mail->send();
Resources:

No comments: