教程栏目

joomla中文网出品的官方教程

如何在自己的组件中使用邮件功能,最近做一个项目需要将用户提交的表单发送邮件。当时还准备自己写邮件发送程序。没想joomla已经准备好了发送邮件的类JMail.

 获得Mail对象

$mailer = JFactory::getMailer();

 


 

设置Sender

		$config = JFactory::getConfig();
		$sender = array(
			$config->get('config.mailfrom'),
			$config->get('config.fromname')
		);
		$mailer->setSender($sender);

 主要调用setSender函数,这个函数接受一个数组作为参数,数组的元素就是发件者的地址和发件者的名称。上面的代码从系统配置中读取,当然我们也可从其他的地方那个读取。另外,请注意,如果是j25,使用getValue而不是get().

个人很反感joomla这种改变。使得代码的兼容性变得极差。长期下去,joomla将会被开发者抛弃!构建系统一定要注意向后的兼容性。

设置收件人

$user = JFactory::getUser();
$recipient = $user->email;
 $mailer->addRecipient($recipient);

 代码思路非常简单,得到当前的用户,然后获得当前用户的邮件地址。如果有多个收件人,那么我们可以使用一个数组存储多个收件人的地址,然后作为参数传递给addRecipient.代码如下:

$recipient = array( 这个 E-mail 受反垃圾邮件程序保护,您需要启用 JavaScript 才能查看。', 这个 E-mail 受反垃圾邮件程序保护,您需要启用 JavaScript 才能查看。', 这个 E-mail 受反垃圾邮件程序保护,您需要启用 JavaScript 才能查看。' );
 
$mailer->addRecipient($recipient);

 


 

创建邮件内容

代码如下:

$body   = "Your body string\nin double quotes if you want to parse the \nnewlines etc";
$mailer->setSubject('Your subject string');
$mailer->setBody($body);
// Optional file attached
$mailer->addAttachment(JPATH_COMPONENT.'/assets/document.pdf');

 当然,如果你要让你的邮件为HTMl格式,那么你需要告诉mailer.你的内容是HTML.我们可以通过指定IsHTML来实现。当你要发送邮件的时候,你需要设置Encoding为base64编码,这样可以避免不必要的字符串输出。

看代码:

body   = '<h2>Our mail</h2>'
    . '<div>A message to our dear readers'
    . '<img src="cid:logo_id" alt="logo"/></div>';
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setBody($body);
// Optionally add embedded image
$mailer->AddEmbeddedImage( JPATH_COMPONENT.'/assets/logo128.jpg', 'logo_id', 'logo.jpg', 'base64', 'image/jpeg' );

 Normally you would leave any images on your server and refer to them with an ordinary HTML image tag, to reduce size of the mail and the time sending it.


发送邮件

$send = $mailer->Send();
if ( $send !== true ) {
    echo 'Error sending email: ' . $send->__toString();
} else {
    echo 'Mail sent';
}

 

You would probably want to write your own error handler, if there is an error sending the mail.

The JMail object is used for sending mail in Joomla's contact manager. See the file joomla/components/com_contact/controller.php

作者: 樱木花道

Joomla程序员,从J1.5到J4.x始终都在做Joomla相关开发定制工作,有超过10年行业经验,国内Joomla扩展开发商ZMAX团队的核心成员

作者网站:ZMAX程序人

评论 (0)

  • 最新在前
  • 最佳在前

第1章 Joomla入门教程

第3章 C计划

第5章 E计划

第6章 H计划

第7章 G计划

第9章 运行环境

第11章 主从与集群

第12章 模块开发

第13章 插件开发

第14章 j2.x组件开发教程

第15章 页面定制教程

第16章 页面构造器