栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

Zend Framework入门教程之Zend_Mail用法示例

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Zend Framework入门教程之Zend_Mail用法示例

本文实例讲述了Zend framework入门教程之Zend_Mail用法。分享给大家供大家参考,具体如下:

Zend_Mail组件提供了通用化的功能来创建和发送文本。

Zend_Mail通过PHP内建的mail()函数或者直接通过SMTP连接来发送邮件。

一个简单的邮件由收件人、主题、邮件内容以及发件人等内容组成。

步骤如下

1.创建对象
2.设置邮件内容
3.发送

案例:

addTo("jiqing9006@126.com","jim");    //添加一个收件人
$my_mail->setSubject("Just a test"); //设置主题
$my_mail->setBodyText("Hello Jim!"); //为邮件设置正文内容
$my_mail->setFrom("706507884@qq.com","jiqing");   //为邮件设置发件人
echo "邮件设置完毕";
echo "

"; echo "邮件收件人为:"; $result = $my_mail->getHeaders(); echo $result['To'][0]; echo "

"; echo "邮件主题为:"; echo $my_mail->getSubject(); echo "

"; echo "邮件内容为:"; $result = $my_mail->getBodyText(); echo $result->getContent(); echo "

"; echo "邮件发件人为:"; echo $my_mail->getFrom(); echo "

"; $my_mail->send();

结果:

邮件设置完毕
邮件收件人为:jim
邮件主题为:Just a test
邮件内容为:Hello Jim!
邮件发件人为:706507884@qq.com

Fatal error: Uncaught exception 'Zend_Mail_Transport_Exception' with message 'Unable to send mail. mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()' in C:zendlibraryZendMailTransportSendmail.php:137 Stack trace: #0 C:zendlibraryZendMailTransportAbstract.php(348): Zend_Mail_Transport_Sendmail->_sendMail() #1 C:zendlibraryZendMail.php(1194): Zend_Mail_Transport_Abstract->send(Object(Zend_Mail)) #2 D:xampphtdocstest.php(24): Zend_Mail->send() #3 {main} thrown in C:zendlibraryZendMailTransportSendmail.php on line 137

点评:

这里执行不能成功,是因为没有配置好Mail服务器。

源码分析:

_charset = $charset;
    }
  }
  
  public function getCharset()
  {
    return $this->_charset;
  }
  
  public function setType($type)
  {
    $allowed = array(
      Zend_Mime::MULTIPART_ALTERNATIVE,
      Zend_Mime::MULTIPART_MIXED,
      Zend_Mime::MULTIPART_RELATED,
    );
    if (!in_array($type, $allowed)) {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('Invalid content type "' . $type . '"');
    }
    $this->_type = $type;
    return $this;
  }
  
  public function getType()
  {
    return $this->_type;
  }
  
  public function setMimeBoundary($boundary)
  {
    $this->_mimeBoundary = $boundary;
    return $this;
  }
  
  public function getMimeBoundary()
  {
    return $this->_mimeBoundary;
  }
  
  public function getEncodingOfHeaders()
  {
    return $this->getHeaderEncoding();
  }
  
  public function getHeaderEncoding()
  {
    return $this->_headerEncoding;
  }
  
  public function setEncodingOfHeaders($encoding)
  {
    return $this->setHeaderEncoding($encoding);
  }
  
  public function setHeaderEncoding($encoding)
  {
    $allowed = array(
      Zend_Mime::ENCODING_base64,
      Zend_Mime::ENCODING_QUOTEDPRINTABLE
    );
    if (!in_array($encoding, $allowed)) {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('Invalid encoding "' . $encoding . '"');
    }
    $this->_headerEncoding = $encoding;
    return $this;
  }
  
  public function setBodyText($txt, $charset = null, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE)
  {
    if ($charset === null) {
      $charset = $this->_charset;
    }
    $mp = new Zend_Mime_Part($txt);
    $mp->encoding = $encoding;
    $mp->type = Zend_Mime::TYPE_TEXT;
    $mp->disposition = Zend_Mime::DISPOSITION_INLINE;
    $mp->charset = $charset;
    $this->_bodyText = $mp;
    return $this;
  }
  
  public function getBodyText($textonly = false)
  {
    if ($textonly && $this->_bodyText) {
      $body = $this->_bodyText;
      return $body->getContent();
    }
    return $this->_bodyText;
  }
  
  public function setBodyHtml($html, $charset = null, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE)
  {
    if ($charset === null) {
      $charset = $this->_charset;
    }
    $mp = new Zend_Mime_Part($html);
    $mp->encoding = $encoding;
    $mp->type = Zend_Mime::TYPE_HTML;
    $mp->disposition = Zend_Mime::DISPOSITION_INLINE;
    $mp->charset = $charset;
    $this->_bodyHtml = $mp;
    return $this;
  }
  
  public function getBodyHtml($htmlonly = false)
  {
    if ($htmlonly && $this->_bodyHtml) {
      $body = $this->_bodyHtml;
      return $body->getContent();
    }
    return $this->_bodyHtml;
  }
  
  public function addAttachment(Zend_Mime_Part $attachment)
  {
    $this->addPart($attachment);
    $this->hasAttachments = true;
    return $this;
  }
  
  public function createAttachment($body,
     $mimeType  = Zend_Mime::TYPE_OCTETSTREAM,
     $disposition = Zend_Mime::DISPOSITION_ATTACHMENT,
     $encoding  = Zend_Mime::ENCODING_base64,
     $filename  = null)
  {
    $mp = new Zend_Mime_Part($body);
    $mp->encoding = $encoding;
    $mp->type = $mimeType;
    $mp->disposition = $disposition;
    $mp->filename = $filename;
    $this->addAttachment($mp);
    return $mp;
  }
  
  public function getPartCount()
  {
    return count($this->_parts);
  }
  
  protected function _encodeHeader($value)
  {
    if (Zend_Mime::isPrintable($value) === false) {
      if ($this->getHeaderEncoding() === Zend_Mime::ENCODING_QUOTEDPRINTABLE) {
 $value = Zend_Mime::encodeQuotedPrintableHeader($value, $this->getCharset(), Zend_Mime::LINELENGTH, Zend_Mime::LINEEND);
      } else {
 $value = Zend_Mime::encodebase64Header($value, $this->getCharset(), Zend_Mime::LINELENGTH, Zend_Mime::LINEEND);
      }
    }
    return $value;
  }
  
  protected function _storeHeader($headerName, $value, $append = false)
  {
    if (isset($this->_headers[$headerName])) {
      $this->_headers[$headerName][] = $value;
    } else {
      $this->_headers[$headerName] = array($value);
    }
    if ($append) {
      $this->_headers[$headerName]['append'] = true;
    }
  }
  
  protected function _clearHeader($headerName)
  {
    $this->clearHeader($headerName);
  }
  
  protected function _addRecipientAndHeader($headerName, $email, $name)
  {
    $email = $this->_filterEmail($email);
    $name = $this->_filterName($name);
    // prevent duplicates
    $this->_recipients[$email] = 1;
    $this->_storeHeader($headerName, $this->_formatAddress($email, $name), true);
  }
  
  public function addTo($email, $name='')
  {
    if (!is_array($email)) {
      $email = array($name => $email);
    }
    foreach ($email as $n => $recipient) {
      $this->_addRecipientAndHeader('To', $recipient, is_int($n) ? '' : $n);
      $this->_to[] = $recipient;
    }
    return $this;
  }
  
  public function addCc($email, $name='')
  {
    if (!is_array($email)) {
      $email = array($name => $email);
    }
    foreach ($email as $n => $recipient) {
      $this->_addRecipientAndHeader('Cc', $recipient, is_int($n) ? '' : $n);
    }
    return $this;
  }
  
  public function addBcc($email)
  {
    if (!is_array($email)) {
      $email = array($email);
    }
    foreach ($email as $recipient) {
      $this->_addRecipientAndHeader('Bcc', $recipient, '');
    }
    return $this;
  }
  
  public function getRecipients()
  {
    return array_keys($this->_recipients);
  }
  
  public function clearHeader($headerName)
  {
    if (isset($this->_headers[$headerName])){
      unset($this->_headers[$headerName]);
    }
    return $this;
  }
  
  public function clearRecipients()
  {
    $this->_recipients = array();
    $this->_to = array();
    $this->clearHeader('To');
    $this->clearHeader('Cc');
    $this->clearHeader('Bcc');
    return $this;
  }
  
  public function setFrom($email, $name = null)
  {
    if (null !== $this->_from) {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('From Header set twice');
    }
    $email = $this->_filterEmail($email);
    $name = $this->_filterName($name);
    $this->_from = $email;
    $this->_storeHeader('From', $this->_formatAddress($email, $name), true);
    return $this;
  }
  
  public function setReplyTo($email, $name = null)
  {
    if (null !== $this->_replyTo) {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('Reply-To Header set twice');
    }
    $email = $this->_filterEmail($email);
    $name = $this->_filterName($name);
    $this->_replyTo = $email;
    $this->_storeHeader('Reply-To', $this->_formatAddress($email, $name), true);
    return $this;
  }
  
  public function getFrom()
  {
    return $this->_from;
  }
  
  public function getReplyTo()
  {
    return $this->_replyTo;
  }
  
  public function clearFrom()
  {
    $this->_from = null;
    $this->clearHeader('From');
    return $this;
  }
   
  public function clearReplyTo()
  {
    $this->_replyTo = null;
    $this->clearHeader('Reply-To');
    return $this;
  }
  
  public static function setDefaultFrom($email, $name = null)
  {
    self::$_defaultFrom = array('email' => $email, 'name' => $name);
  }
  
  public static function getDefaultFrom()
  {
    return self::$_defaultFrom;
  }
  
  public static function clearDefaultFrom()
  {
    self::$_defaultFrom = null;
  }
  
  public function setFromToDefaultFrom() {
    $from = self::getDefaultFrom();
    if($from === null) {
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception(
 'No default From Address set to use');
    }
    $this->setFrom($from['email'], $from['name']);
    return $this;
  }
  
  public static function setDefaultReplyTo($email, $name = null)
  {
    self::$_defaultReplyTo = array('email' => $email, 'name' => $name);
  }
  
  public static function getDefaultReplyTo()
  {
    return self::$_defaultReplyTo;
  }
  
  public static function clearDefaultReplyTo()
  {
    self::$_defaultReplyTo = null;
  }
  
  public function setReplyToFromDefault() {
    $replyTo = self::getDefaultReplyTo();
    if($replyTo === null) {
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception(
 'No default Reply-To Address set to use');
    }
    $this->setReplyTo($replyTo['email'], $replyTo['name']);
    return $this;
  }
  
  public function setReturnPath($email)
  {
    if ($this->_returnPath === null) {
      $email = $this->_filterEmail($email);
      $this->_returnPath = $email;
      $this->_storeHeader('Return-Path', $email, false);
    } else {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('Return-Path Header set twice');
    }
    return $this;
  }
  
  public function getReturnPath()
  {
    if (null !== $this->_returnPath) {
      return $this->_returnPath;
    }
    return $this->_from;
  }
  
  public function clearReturnPath()
  {
    $this->_returnPath = null;
    $this->clearHeader('Return-Path');
    return $this;
  }
  
  public function setSubject($subject)
  {
    if ($this->_subject === null) {
      $subject = $this->_filterOther($subject);
      $this->_subject = $this->_encodeHeader($subject);
      $this->_storeHeader('Subject', $this->_subject);
    } else {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('Subject set twice');
    }
    return $this;
  }
  
  public function getSubject()
  {
    return $this->_subject;
  }
  
  public function clearSubject()
  {
    $this->_subject = null;
    $this->clearHeader('Subject');
    return $this;
  }
  
  public function setDate($date = null)
  {
    if ($this->_date === null) {
      if ($date === null) {
 $date = date('r');
      } else if (is_int($date)) {
 $date = date('r', $date);
      } else if (is_string($date)) {
 $date = strtotime($date);
 if ($date === false || $date < 0) {
   
   require_once 'Zend/Mail/Exception.php';
   throw new Zend_Mail_Exception('String representations of Date Header must be ' .
    'strtotime()-compatible');
 }
 $date = date('r', $date);
      } else if ($date instanceof Zend_Date) {
 $date = $date->get(Zend_Date::RFC_2822);
      } else {
 
 require_once 'Zend/Mail/Exception.php';
 throw new Zend_Mail_Exception(__METHOD__ . ' only accepts UNIX timestamps, Zend_Date objects, ' .
  ' and strtotime()-compatible strings');
      }
      $this->_date = $date;
      $this->_storeHeader('Date', $date);
    } else {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('Date Header set twice');
    }
    return $this;
  }
  
  public function getDate()
  {
    return $this->_date;
  }
  
  public function clearDate()
  {
    $this->_date = null;
    $this->clearHeader('Date');
    return $this;
  }
  
  public function setMessageId($id = true)
  {
    if ($id === null || $id === false) {
      return $this;
    } elseif ($id === true) {
      $id = $this->createMessageId();
    }
    if ($this->_messageId === null) {
      $id = $this->_filterOther($id);
      $this->_messageId = $id;
      $this->_storeHeader('Message-Id', '<' . $this->_messageId . '>');
    } else {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('Message-ID set twice');
    }
    return $this;
  }
  
  public function getMessageId()
  {
    return $this->_messageId;
  }
  
  public function clearMessageId()
  {
    $this->_messageId = null;
    $this->clearHeader('Message-Id');
    return $this;
  }
  
  public function createMessageId() {
    $time = time();
    if ($this->_from !== null) {
      $user = $this->_from;
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
      $user = $_SERVER['REMOTE_ADDR'];
    } else {
      $user = getmypid();
    }
    $rand = mt_rand();
    if ($this->_recipients !== array()) {
      $recipient = array_rand($this->_recipients);
    } else {
      $recipient = 'unknown';
    }
    if (isset($_SERVER["SERVER_NAME"])) {
      $hostName = $_SERVER["SERVER_NAME"];
    } else {
      $hostName = php_uname('n');
    }
    return sha1($time . $user . $rand . $recipient) . '@' . $hostName;
  }
  
  public function addHeader($name, $value, $append = false)
  {
    $prohibit = array('to', 'cc', 'bcc', 'from', 'subject',
      'reply-to', 'return-path',
      'date', 'message-id',
      );
    if (in_array(strtolower($name), $prohibit)) {
      
      require_once 'Zend/Mail/Exception.php';
      throw new Zend_Mail_Exception('Cannot set standard header from addHeader()');
    }
    $value = $this->_filterOther($value);
    $value = $this->_encodeHeader($value);
    $this->_storeHeader($name, $value, $append);
    return $this;
  }
  
  public function getHeaders()
  {
    return $this->_headers;
  }
  
  public function send($transport = null)
  {
    if ($transport === null) {
      if (! self::$_defaultTransport instanceof Zend_Mail_Transport_Abstract) {
 require_once 'Zend/Mail/Transport/Sendmail.php';
 $transport = new Zend_Mail_Transport_Sendmail();
      } else {
 $transport = self::$_defaultTransport;
      }
    }
    if ($this->_date === null) {
      $this->setDate();
    }
    if(null === $this->_from && null !== self::getDefaultFrom()) {
      $this->setFromToDefaultFrom();
    }
    if(null === $this->_replyTo && null !== self::getDefaultReplyTo()) {
      $this->setReplyToFromDefault();
    }
    $transport->send($this);
    return $this;
  }
  
  protected function _filterEmail($email)
  {
    $rule = array("r" => '',
    "n" => '',
    "t" => '',
    '"' => '',
    ',' => '',
    '<' => '',
    '>' => '',
    );
    return strtr($email, $rule);
  }
  
  protected function _filterName($name)
  {
    $rule = array("r" => '',
    "n" => '',
    "t" => '',
    '"' => "'",
    '<' => '[',
    '>' => ']',
    );
    return trim(strtr($name, $rule));
  }
  
  protected function _filterOther($data)
  {
    $rule = array("r" => '',
    "n" => '',
    "t" => '',
    );
    return strtr($data, $rule);
  }
  
  protected function _formatAddress($email, $name)
  {
    if ($name === '' || $name === null || $name === $email) {
      return $email;
    } else {
      $encodedName = $this->_encodeHeader($name);
      if ($encodedName === $name && strcspn($name, '()<>[]:;@\,') != strlen($name)) {
 $format = '"%s" <%s>';
      } else {
 $format = '%s <%s>';
      }
      return sprintf($format, $encodedName, $email);
    }
  }
}

更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend frameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Zend framework框架的PHP程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/41869.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号