当前位置:   article > 正文

phpmailer发邮件常见的一些问题总结及使用案例_宝塔搭建 phpmailer 邮件无法发送

宝塔搭建 phpmailer 邮件无法发送


PHPMailer邮件类使用错误分析

一,没有定义发送邮箱$mail->From或格式不正确,错误提示:Language string failed to load: recipients_failed test@test.com,注意,这个配置一定要正确,而且是正确的邮箱

二,没有定义邮件服务主机$mail->Host或连接失败,错误提示:Language string failed to load: connect_host

三,没有定义发送邮箱$mail->AddAddress或邮箱格式不正确,错误提示:Language string failed to load: provide_address

四,没有定义邮箱发送用户名$mail->Username,错误提示:Language string failed to load: connect_host

五,没有定义邮箱发送密码$mail->Password,错误提示:Language string failed to load: connect_host,这类错误非常明显,一般都是邮箱服务器配置不正确不能边接。

六,邮件正文编码,如果发送HTML邮件,需要定义正确的编码格式和字符,发送GBK邮件如下:
$mail->IsHTML ( true ); 是否支持HTML邮件
$mail->CharSet = "GB2312"; 字符设置
$mail->Encoding = "base64"; 编码方式
配置后可直接发送HTML邮件,如下:

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  4. <title>PHPMailer邮件测试</title>
  5. </head>
  6. <body>
  7. <div>PHPMailer邮件类使用错误分析</div>
  8. </body>
  9. </html>

七,学会正确使用错误提示$mail->ErrorInfo查看邮件错误,可直接查找问题。

使用PHPMailer邮件类发送邮件使用非常简单,基本配置如上所示,在使用过程中正确了解错误提示,并及时了解错误原因,对于正确使用PHPMailer邮件类来说非常重要。

==========================================================================

这几天做mail群发,碰到不少问题。一些常见的错误网上很多但没有答案,靠自己不断的尝试终于OK了~这里把几个常见的问题列出来做为工作笔记!
     要做发送邮件功能,首先要明白邮件收发的原理,引用网友一段话比较容易懂:

  1. 在Internet上将一段文本信息从一台计算机传送到另一台计算机上,可通过两种协议来完成,即SMTP(Simple Mail Transfer Protocol,简单邮件传输协议)和POP3(Post Office Protocol,邮局协议3)。SMTP是Internet协议集中的邮件标准。在Internet上能够接收电子邮件的服务器都有SMTP。电子邮件在发送前,发件方的SMTP服务器与接收方的SMTP服务器联系,确认接收方准备好了,则开始邮件传递;若没有准备好,发送服务器便会等待,并在一段时间后继续与接收方邮件服务器联系。这种方式在Internet上称为“存储——转发”方式。POP3可允许E-mail客户向某一SMTP服务器发送电子邮件,另外,也可以接收来自SMTP服务器的电子邮件。换句话说,电子邮件在客户PC机与服务提供商之间的传递是通过P0P3来完成的,而电子邮件在 Internet上的传递则是通过SMTP来实现。  
在Internet上将一段文本信息从一台计算机传送到另一台计算机上,可通过两种协议来完成,即SMTP(Simple Mail Transfer Protocol,简单邮件传输协议)和POP3(Post Office Protocol,邮局协议3)。SMTP是Internet协议集中的邮件标准。在Internet上能够接收电子邮件的服务器都有SMTP。电子邮件在发送前,发件方的SMTP服务器与接收方的SMTP服务器联系,确认接收方准备好了,则开始邮件传递;若没有准备好,发送服务器便会等待,并在一段时间后继续与接收方邮件服务器联系。这种方式在Internet上称为“存储——转发”方式。POP3可允许E-mail客户向某一SMTP服务器发送电子邮件,另外,也可以接收来自SMTP服务器的电子邮件。换句话说,电子邮件在客户PC机与服务提供商之间的传递是通过P0P3来完成的,而电子邮件在 Internet上的传递则是通过SMTP来实现。


如果觉得不够清楚的话,则引用网上的一张图来解释吧:

有关phpmailer的介绍可以参考官网:http://phpmailer.codeworxtech.com/

常见异常:

1.SMTP Error: Could not authenticate.

   这个是因为smtp验证没通过,就是smtp server 的用户名和密码不正确了

  1. $mail->Username = "smtp@163.com"; // SMTP server username
  2. t;Password = "******";
  3. $mail->Username = "smtp@163.com"; // SMTP server username $mail->Password = "******";

2.Could not execute: /usr/sbin/sendmail

    这是因为

  1. $mail->IsSendmail(); // tell the class to use Sendmail
  2. $mail->IsSendmail(); // tell the class to use Sendmail

   去掉上面的代码就ok了!(PHP同理)

3.关于phpmailer发送邮件产生中文乱码问题

环境一:在普通环境,即标题内容等含中文的内容是在脚本中加上去的,或从文本中获取的,只需要进行如下操作(网上有很多):
   修改class.phpmailer.php中的EncodeHeader函数,改为:

  1. public function EncodeHeader($str, $position = 'text', $pl = 0) {
  2. $x = 0;
  3. if ($pl){return "=?".$this->CharSet."?B?".base64_encode($str)."?=";}
  4. public function EncodeHeader($str, $position = 'text', $pl = 0) { $x = 0; if ($pl){return "=?".$this->CharSet."?B?".base64_encode($str)."?=";}

再改下使用这个函数的一段:

  1. if($this->Mailer != 'mail') {
  2. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject),'text',1));
  3. }
  4. if($this->Mailer != 'mail') { $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject),'text',1)); }

当然编码设置也不能少了:
  1. $mail->CharSet="utf-8";
  2. $mail->Encoding = "base64";
  3. $mail->CharSet="utf-8"; $mail->Encoding = "base64";

环境二:从excel中提取内容然后再发送excel中的内容给用户,这个折腾了我好久。最终找到解决办法了。最关键的地方是:excel中的编码是html格式的unicode,所以得使用下面这个函数将其转化为utf8,这个帖子的最后回复的人帮了我,谢谢他!帖子地址是:http://www.phpchina.com/bbs/viewthread.php?tid=111554

  1. private function uc2html($str)
  2. {
  3. $ret = '';
  4. for( $i=0; $i<strlen($str)/2; $i++ )
  5. {
  6. $charcode = ord($str[$i*2])+256*ord($str[$i*2+1]);
  7. $ret .= '&#'.$charcode.';';
  8. }
  9. return mb_convert_encoding($ret,'UTF-8','HTML-ENTITIES');
  10. }
  11. private function uc2html($str) { $ret = ''; for( $i=0; $i<strlen($str)/2; $i++ ) { $charcode = ord($str[$i*2])+256*ord($str[$i*2+1]); $ret .= '&#'.$charcode.';'; } return mb_convert_encoding($ret,'UTF-8','HTML-ENTITIES'); }

下面贴段测试代码:

  1. <?php
  2. /**
  3. * Simple example script using PHPMailer with exceptions enabled
  4. * @package phpmailer
  5. * @version $Id$
  6. */
  7. require '../class.phpmailer.php';
  8. try {
  9. $mail = new PHPMailer(true); //New instance, with exceptions enabled
  10. $body = file_get_contents('contents.html');
  11. $body = preg_replace('/\\\\/','', $body); //Strip backslashes
  12. $mail->IsSMTP(); // tell the class to use SMTP
  13. $mail->SMTPAuth = true; // enable SMTP authentication
  14. $mail->Port = 25; // set the SMTP server port
  15. $mail->Host = "smtp.xxxx.com"; // SMTP server
  16. $mail->Username = "xxx@xxx.com"; // SMTP server username
  17. $mail->Password = "xxxx"; // SMTP server password
  18. $mail->IsSendmail(); // tell the class to use Sendmail
  19. $mail->AddReplyTo("xxx@sina.com","xxxx");
  20. $mail->From = "xxxx@m6699.com";
  21. $mail->FromName = "DJB";
  22. $to = "xxx@sina.com";
  23. $mail->AddAddress($to);
  24. $mail->Subject = "First PHPMailer Message";
  25. $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
  26. $mail->WordWrap = 80; // set word wrap
  27. $mail->MsgHTML($body);
  28. $mail->IsHTML(true); // send as HTML
  29. $mail->Send();
  30. echo 'Message has been sent.';
  31. } catch (phpmailerException $e) {
  32. echo $e->errorMessage();
  33. }
  34. ?>

phpmailer文件源码(下载地址:http://sourceforge.net/projects/phpmailer/)

一.class.phpmailer.php文件

  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.1 |
  6. | Contact: via sourceforge.net support pages (also www.worxware.com) |
  7. | Info: http://phpmailer.sourceforge.net |
  8. | Support: http://sourceforge.net/projects/phpmailer/ |
  9. | ------------------------------------------------------------------------- |
  10. | Admin: Andy Prevost (project admininistrator) |
  11. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  12. | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
  13. | Founder: Brent R. Matzelle (original founder) |
  14. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  15. | Copyright (c) 2001-2003, Brent R. Matzelle |
  16. | ------------------------------------------------------------------------- |
  17. | License: Distributed under the Lesser General Public License (LGPL) |
  18. | http://www.gnu.org/copyleft/lesser.html |
  19. | This program is distributed in the hope that it will be useful - WITHOUT |
  20. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  21. | FITNESS FOR A PARTICULAR PURPOSE. |
  22. | ------------------------------------------------------------------------- |
  23. | We offer a number of paid services (www.worxware.com): |
  24. | - Web Hosting on highly optimized fast and secure servers |
  25. | - Technology Consulting |
  26. | - Oursourcing (highly qualified programmers and graphic designers) |
  27. '---------------------------------------------------------------------------'
  28. */
  29. /**
  30. * PHPMailer - PHP email transport class
  31. * NOTE: Requires PHP version 5 or later
  32. * @package PHPMailer
  33. * @author Andy Prevost
  34. * @author Marcus Bointon
  35. * @copyright 2004 - 2009 Andy Prevost
  36. * @version $Id: class.phpmailer.php 447 2009-05-25 01:36:38Z codeworxtech $
  37. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  38. */
  39. if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
  40. class PHPMailer {
  41. /
  42. // PROPERTIES, PUBLIC
  43. /
  44. /**
  45. * Email priority (1 = High, 3 = Normal, 5 = low).
  46. * @var int
  47. */
  48. public $Priority = 3;
  49. /**
  50. * Sets the CharSet of the message.
  51. * @var string
  52. */
  53. public $CharSet = 'iso-8859-1';
  54. /**
  55. * Sets the Content-type of the message.
  56. * @var string
  57. */
  58. public $ContentType = 'text/plain';
  59. /**
  60. * Sets the Encoding of the message. Options for this are
  61. * "8bit", "7bit", "binary", "base64", and "quoted-printable".
  62. * @var string
  63. */
  64. public $Encoding = '8bit';
  65. /**
  66. * Holds the most recent mailer error message.
  67. * @var string
  68. */
  69. public $ErrorInfo = '';
  70. /**
  71. * Sets the From email address for the message.
  72. * @var string
  73. */
  74. public $From = 'root@localhost';
  75. /**
  76. * Sets the From name of the message.
  77. * @var string
  78. */
  79. public $FromName = 'Root User';
  80. /**
  81. * Sets the Sender email (Return-Path) of the message. If not empty,
  82. * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  83. * @var string
  84. */
  85. public $Sender = '';
  86. /**
  87. * Sets the Subject of the message.
  88. * @var string
  89. */
  90. public $Subject = '';
  91. /**
  92. * Sets the Body of the message. This can be either an HTML or text body.
  93. * If HTML then run IsHTML(true).
  94. * @var string
  95. */
  96. public $Body = '';
  97. /**
  98. * Sets the text-only body of the message. This automatically sets the
  99. * email to multipart/alternative. This body can be read by mail
  100. * clients that do not have HTML email capability such as mutt. Clients
  101. * that can read HTML will view the normal Body.
  102. * @var string
  103. */
  104. public $AltBody = '';
  105. /**
  106. * Sets word wrapping on the body of the message to a given number of
  107. * characters.
  108. * @var int
  109. */
  110. public $WordWrap = 0;
  111. /**
  112. * Method to send mail: ("mail", "sendmail", or "smtp").
  113. * @var string
  114. */
  115. public $Mailer = 'mail';
  116. /**
  117. * Sets the path of the sendmail program.
  118. * @var string
  119. */
  120. public $Sendmail = '/usr/sbin/sendmail';
  121. /**
  122. * Path to PHPMailer plugins. Useful if the SMTP class
  123. * is in a different directory than the PHP include path.
  124. * @var string
  125. */
  126. public $PluginDir = '';
  127. /**
  128. * Sets the email address that a reading confirmation will be sent.
  129. * @var string
  130. */
  131. public $ConfirmReadingTo = '';
  132. /**
  133. * Sets the hostname to use in Message-Id and Received headers
  134. * and as default HELO string. If empty, the value returned
  135. * by SERVER_NAME is used or 'localhost.localdomain'.
  136. * @var string
  137. */
  138. public $Hostname = '';
  139. /**
  140. * Sets the message ID to be used in the Message-Id header.
  141. * If empty, a unique id will be generated.
  142. * @var string
  143. */
  144. public $MessageID = '';
  145. /
  146. // PROPERTIES FOR SMTP
  147. /
  148. /**
  149. * Sets the SMTP hosts. All hosts must be separated by a
  150. * semicolon. You can also specify a different port
  151. * for each host by using this format: [hostname:port]
  152. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  153. * Hosts will be tried in order.
  154. * @var string
  155. */
  156. public $Host = 'localhost';
  157. /**
  158. * Sets the default SMTP server port.
  159. * @var int
  160. */
  161. public $Port = 25;
  162. /**
  163. * Sets the SMTP HELO of the message (Default is $Hostname).
  164. * @var string
  165. */
  166. public $Helo = '';
  167. /**
  168. * Sets connection prefix.
  169. * Options are "", "ssl" or "tls"
  170. * @var string
  171. */
  172. public $SMTPSecure = '';
  173. /**
  174. * Sets SMTP authentication. Utilizes the Username and Password variables.
  175. * @var bool
  176. */
  177. public $SMTPAuth = false;
  178. /**
  179. * Sets SMTP username.
  180. * @var string
  181. */
  182. public $Username = '';
  183. /**
  184. * Sets SMTP password.
  185. * @var string
  186. */
  187. public $Password = '';
  188. /**
  189. * Sets the SMTP server timeout in seconds.
  190. * This function will not work with the win32 version.
  191. * @var int
  192. */
  193. public $Timeout = 10;
  194. /**
  195. * Sets SMTP class debugging on or off.
  196. * @var bool
  197. */
  198. public $SMTPDebug = false;
  199. /**
  200. * Prevents the SMTP connection from being closed after each mail
  201. * sending. If this is set to true then to close the connection
  202. * requires an explicit call to SmtpClose().
  203. * @var bool
  204. */
  205. public $SMTPKeepAlive = false;
  206. /**
  207. * Provides the ability to have the TO field process individual
  208. * emails, instead of sending to entire TO addresses
  209. * @var bool
  210. */
  211. public $SingleTo = false;
  212. /**
  213. * If SingleTo is true, this provides the array to hold the email addresses
  214. * @var bool
  215. */
  216. public $SingleToArray = array();
  217. /**
  218. * Provides the ability to change the line ending
  219. * @var string
  220. */
  221. public $LE = "\n";
  222. /**
  223. * Used with DKIM DNS Resource Record
  224. * @var string
  225. */
  226. public $DKIM_selector = 'phpmailer';
  227. /**
  228. * Used with DKIM DNS Resource Record
  229. * optional, in format of email address 'you@yourdomain.com'
  230. * @var string
  231. */
  232. public $DKIM_identity = '';
  233. /**
  234. * Used with DKIM DNS Resource Record
  235. * optional, in format of email address 'you@yourdomain.com'
  236. * @var string
  237. */
  238. public $DKIM_domain = '';
  239. /**
  240. * Used with DKIM DNS Resource Record
  241. * optional, in format of email address 'you@yourdomain.com'
  242. * @var string
  243. */
  244. public $DKIM_private = '';
  245. /**
  246. * Callback Action function name
  247. * the function that handles the result of the send email action. Parameters:
  248. * bool $result result of the send action
  249. * string $to email address of the recipient
  250. * string $cc cc email addresses
  251. * string $bcc bcc email addresses
  252. * string $subject the subject
  253. * string $body the email body
  254. * @var string
  255. */
  256. public $action_function = ''; //'callbackAction';
  257. /**
  258. * Sets the PHPMailer Version number
  259. * @var string
  260. */
  261. public $Version = '5.1';
  262. /
  263. // PROPERTIES, PRIVATE AND PROTECTED
  264. /
  265. private $smtp = NULL;
  266. private $to = array();
  267. private $cc = array();
  268. private $bcc = array();
  269. private $ReplyTo = array();
  270. private $all_recipients = array();
  271. private $attachment = array();
  272. private $CustomHeader = array();
  273. private $message_type = '';
  274. private $boundary = array();
  275. protected $language = array();
  276. private $error_count = 0;
  277. private $sign_cert_file = "";
  278. private $sign_key_file = "";
  279. private $sign_key_pass = "";
  280. private $exceptions = false;
  281. /
  282. // CONSTANTS
  283. /
  284. const STOP_MESSAGE = 0; // message only, continue processing
  285. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  286. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  287. /
  288. // METHODS, VARIABLES
  289. /
  290. /**
  291. * Constructor
  292. * @param boolean $exceptions Should we throw external exceptions?
  293. */
  294. public function __construct($exceptions = false) {
  295. $this->exceptions = ($exceptions == true);
  296. }
  297. /**
  298. * Sets message type to HTML.
  299. * @param bool $ishtml
  300. * @return void
  301. */
  302. public function IsHTML($ishtml = true) {
  303. if ($ishtml) {
  304. $this->ContentType = 'text/html';
  305. } else {
  306. $this->ContentType = 'text/plain';
  307. }
  308. }
  309. /**
  310. * Sets Mailer to send message using SMTP.
  311. * @return void
  312. */
  313. public function IsSMTP() {
  314. $this->Mailer = 'smtp';
  315. }
  316. /**
  317. * Sets Mailer to send message using PHP mail() function.
  318. * @return void
  319. */
  320. public function IsMail() {
  321. $this->Mailer = 'mail';
  322. }
  323. /**
  324. * Sets Mailer to send message using the $Sendmail program.
  325. * @return void
  326. */
  327. public function IsSendmail() {
  328. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  329. $this->Sendmail = '/var/qmail/bin/sendmail';
  330. }
  331. $this->Mailer = 'sendmail';
  332. }
  333. /**
  334. * Sets Mailer to send message using the qmail MTA.
  335. * @return void
  336. */
  337. public function IsQmail() {
  338. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  339. $this->Sendmail = '/var/qmail/bin/sendmail';
  340. }
  341. $this->Mailer = 'sendmail';
  342. }
  343. /
  344. // METHODS, RECIPIENTS
  345. /
  346. /**
  347. * Adds a "To" address.
  348. * @param string $address
  349. * @param string $name
  350. * @return boolean true on success, false if address already used
  351. */
  352. public function AddAddress($address, $name = '') {
  353. return $this->AddAnAddress('to', $address, $name);
  354. }
  355. /**
  356. * Adds a "Cc" address.
  357. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  358. * @param string $address
  359. * @param string $name
  360. * @return boolean true on success, false if address already used
  361. */
  362. public function AddCC($address, $name = '') {
  363. return $this->AddAnAddress('cc', $address, $name);
  364. }
  365. /**
  366. * Adds a "Bcc" address.
  367. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  368. * @param string $address
  369. * @param string $name
  370. * @return boolean true on success, false if address already used
  371. */
  372. public function AddBCC($address, $name = '') {
  373. return $this->AddAnAddress('bcc', $address, $name);
  374. }
  375. /**
  376. * Adds a "Reply-to" address.
  377. * @param string $address
  378. * @param string $name
  379. * @return boolean
  380. */
  381. public function AddReplyTo($address, $name = '') {
  382. return $this->AddAnAddress('ReplyTo', $address, $name);
  383. }
  384. /**
  385. * Adds an address to one of the recipient arrays
  386. * Addresses that have been added already return false, but do not throw exceptions
  387. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  388. * @param string $address The email address to send to
  389. * @param string $name
  390. * @return boolean true on success, false if address already used or invalid in some way
  391. * @access private
  392. */
  393. private function AddAnAddress($kind, $address, $name = '') {
  394. if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
  395. echo 'Invalid recipient array: ' . kind;
  396. return false;
  397. }
  398. $address = trim($address);
  399. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  400. if (!self::ValidateAddress($address)) {
  401. $this->SetError($this->Lang('invalid_address').': '. $address);
  402. if ($this->exceptions) {
  403. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  404. }
  405. echo $this->Lang('invalid_address').': '.$address;
  406. return false;
  407. }
  408. if ($kind != 'ReplyTo') {
  409. if (!isset($this->all_recipients[strtolower($address)])) {
  410. array_push($this->$kind, array($address, $name));
  411. $this->all_recipients[strtolower($address)] = true;
  412. return true;
  413. }
  414. } else {
  415. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  416. $this->ReplyTo[strtolower($address)] = array($address, $name);
  417. return true;
  418. }
  419. }
  420. return false;
  421. }
  422. /**
  423. * Set the From and FromName properties
  424. * @param string $address
  425. * @param string $name
  426. * @return boolean
  427. */
  428. public function SetFrom($address, $name = '',$auto=1) {
  429. $address = trim($address);
  430. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  431. if (!self::ValidateAddress($address)) {
  432. $this->SetError($this->Lang('invalid_address').': '. $address);
  433. if ($this->exceptions) {
  434. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  435. }
  436. echo $this->Lang('invalid_address').': '.$address;
  437. return false;
  438. }
  439. $this->From = $address;
  440. $this->FromName = $name;
  441. if ($auto) {
  442. if (empty($this->ReplyTo)) {
  443. $this->AddAnAddress('ReplyTo', $address, $name);
  444. }
  445. if (empty($this->Sender)) {
  446. $this->Sender = $address;
  447. }
  448. }
  449. return true;
  450. }
  451. /**
  452. * Check that a string looks roughly like an email address should
  453. * Static so it can be used without instantiation
  454. * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
  455. * Conforms approximately to RFC2822
  456. * @link http://www.hexillion.com/samples/#Regex Original pattern found here
  457. * @param string $address The email address to check
  458. * @return boolean
  459. * @static
  460. * @access public
  461. */
  462. public static function ValidateAddress($address) {
  463. if (function_exists('filter_var')) { //Introduced in PHP 5.2
  464. if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
  465. return false;
  466. } else {
  467. return true;
  468. }
  469. } else {
  470. return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
  471. }
  472. }
  473. /
  474. // METHODS, MAIL SENDING
  475. /
  476. /**
  477. * Creates message and assigns Mailer. If the message is
  478. * not sent successfully then it returns false. Use the ErrorInfo
  479. * variable to view description of the error.
  480. * @return bool
  481. */
  482. public function Send() {
  483. try {
  484. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  485. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  486. }
  487. // Set whether the message is multipart/alternative
  488. if(!empty($this->AltBody)) {
  489. $this->ContentType = 'multipart/alternative';
  490. }
  491. $this->error_count = 0; // reset errors
  492. $this->SetMessageType();
  493. $header = $this->CreateHeader();
  494. $body = $this->CreateBody();
  495. if (empty($this->Body)) {
  496. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  497. }
  498. // digitally sign with DKIM if enabled
  499. if ($this->DKIM_domain && $this->DKIM_private) {
  500. $header_dkim = $this->DKIM_Add($header,$this->Subject,$body);
  501. $header = str_replace("\r\n","\n",$header_dkim) . $header;
  502. }
  503. // Choose the mailer and send through it
  504. switch($this->Mailer) {
  505. case 'sendmail':
  506. return $this->SendmailSend($header, $body);
  507. case 'smtp':
  508. return $this->SmtpSend($header, $body);
  509. default:
  510. return $this->MailSend($header, $body);
  511. }
  512. } catch (phpmailerException $e) {
  513. $this->SetError($e->getMessage());
  514. if ($this->exceptions) {
  515. throw $e;
  516. }
  517. echo $e->getMessage()."\n";
  518. return false;
  519. }
  520. }
  521. /**
  522. * Sends mail using the $Sendmail program.
  523. * @param string $header The message headers
  524. * @param string $body The message body
  525. * @access protected
  526. * @return bool
  527. */
  528. protected function SendmailSend($header, $body) {
  529. if ($this->Sender != '') {
  530. $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  531. } else {
  532. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  533. }
  534. if ($this->SingleTo === true) {
  535. foreach ($this->SingleToArray as $key => $val) {
  536. if(!@$mail = popen($sendmail, 'w')) {
  537. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  538. }
  539. fputs($mail, "To: " . $val . "\n");
  540. fputs($mail, $header);
  541. fputs($mail, $body);
  542. $result = pclose($mail);
  543. // implement call back function if it exists
  544. $isSent = ($result == 0) ? 1 : 0;
  545. $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
  546. if($result != 0) {
  547. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  548. }
  549. }
  550. } else {
  551. if(!@$mail = popen($sendmail, 'w')) {
  552. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  553. }
  554. fputs($mail, $header);
  555. fputs($mail, $body);
  556. $result = pclose($mail);
  557. // implement call back function if it exists
  558. $isSent = ($result == 0) ? 1 : 0;
  559. $this->doCallback($isSent,$this->to,$this->cc,$this->bcc,$this->Subject,$body);
  560. if($result != 0) {
  561. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  562. }
  563. }
  564. return true;
  565. }
  566. /**
  567. * Sends mail using the PHP mail() function.
  568. * @param string $header The message headers
  569. * @param string $body The message body
  570. * @access protected
  571. * @return bool
  572. */
  573. protected function MailSend($header, $body) {
  574. $toArr = array();
  575. foreach($this->to as $t) {
  576. $toArr[] = $this->AddrFormat($t);
  577. }
  578. $to = implode(', ', $toArr);
  579. $params = sprintf("-oi -f %s", $this->Sender);
  580. if ($this->Sender != '' && strlen(ini_get('safe_mode'))< 1) {
  581. $old_from = ini_get('sendmail_from');
  582. ini_set('sendmail_from', $this->Sender);
  583. if ($this->SingleTo === true && count($toArr) > 1) {
  584. foreach ($toArr as $key => $val) {
  585. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  586. // implement call back function if it exists
  587. $isSent = ($rt == 1) ? 1 : 0;
  588. $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
  589. }
  590. } else {
  591. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  592. // implement call back function if it exists
  593. $isSent = ($rt == 1) ? 1 : 0;
  594. $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
  595. }
  596. } else {
  597. if ($this->SingleTo === true && count($toArr) > 1) {
  598. foreach ($toArr as $key => $val) {
  599. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  600. // implement call back function if it exists
  601. $isSent = ($rt == 1) ? 1 : 0;
  602. $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
  603. }
  604. } else {
  605. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
  606. // implement call back function if it exists
  607. $isSent = ($rt == 1) ? 1 : 0;
  608. $this->doCallback($isSent,$to,$this->cc,$this->bcc,$this->Subject,$body);
  609. }
  610. }
  611. if (isset($old_from)) {
  612. ini_set('sendmail_from', $old_from);
  613. }
  614. if(!$rt) {
  615. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  616. }
  617. return true;
  618. }
  619. /**
  620. * Sends mail via SMTP using PhpSMTP
  621. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  622. * @param string $header The message headers
  623. * @param string $body The message body
  624. * @uses SMTP
  625. * @access protected
  626. * @return bool
  627. */
  628. protected function SmtpSend($header, $body) {
  629. require_once $this->PluginDir . 'class.smtp.php';
  630. $bad_rcpt = array();
  631. if(!$this->SmtpConnect()) {
  632. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  633. }
  634. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  635. if(!$this->smtp->Mail($smtp_from)) {
  636. throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
  637. }
  638. // Attempt to send attach all recipients
  639. foreach($this->to as $to) {
  640. if (!$this->smtp->Recipient($to[0])) {
  641. $bad_rcpt[] = $to[0];
  642. // implement call back function if it exists
  643. $isSent = 0;
  644. $this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
  645. } else {
  646. // implement call back function if it exists
  647. $isSent = 1;
  648. $this->doCallback($isSent,$to[0],'','',$this->Subject,$body);
  649. }
  650. }
  651. foreach($this->cc as $cc) {
  652. if (!$this->smtp->Recipient($cc[0])) {
  653. $bad_rcpt[] = $cc[0];
  654. // implement call back function if it exists
  655. $isSent = 0;
  656. $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
  657. } else {
  658. // implement call back function if it exists
  659. $isSent = 1;
  660. $this->doCallback($isSent,'',$cc[0],'',$this->Subject,$body);
  661. }
  662. }
  663. foreach($this->bcc as $bcc) {
  664. if (!$this->smtp->Recipient($bcc[0])) {
  665. $bad_rcpt[] = $bcc[0];
  666. // implement call back function if it exists
  667. $isSent = 0;
  668. $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
  669. } else {
  670. // implement call back function if it exists
  671. $isSent = 1;
  672. $this->doCallback($isSent,'','',$bcc[0],$this->Subject,$body);
  673. }
  674. }
  675. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  676. $badaddresses = implode(', ', $bad_rcpt);
  677. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  678. }
  679. if(!$this->smtp->Data($header . $body)) {
  680. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  681. }
  682. if($this->SMTPKeepAlive == true) {
  683. $this->smtp->Reset();
  684. }
  685. return true;
  686. }
  687. /**
  688. * Initiates a connection to an SMTP server.
  689. * Returns false if the operation failed.
  690. * @uses SMTP
  691. * @access public
  692. * @return bool
  693. */
  694. public function SmtpConnect() {
  695. if(is_null($this->smtp)) {
  696. $this->smtp = new SMTP();
  697. }
  698. $this->smtp->do_debug = $this->SMTPDebug;
  699. $hosts = explode(';', $this->Host);
  700. $index = 0;
  701. $connection = $this->smtp->Connected();
  702. // Retry while there is no connection
  703. try {
  704. while($index < count($hosts) && !$connection) {
  705. $hostinfo = array();
  706. if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
  707. $host = $hostinfo[1];
  708. $port = $hostinfo[2];
  709. } else {
  710. $host = $hosts[$index];
  711. $port = $this->Port;
  712. }
  713. $tls = ($this->SMTPSecure == 'tls');
  714. $ssl = ($this->SMTPSecure == 'ssl');
  715. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
  716. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  717. $this->smtp->Hello($hello);
  718. if ($tls) {
  719. if (!$this->smtp->StartTLS()) {
  720. throw new phpmailerException($this->Lang('tls'));
  721. }
  722. //We must resend HELO after tls negotiation
  723. $this->smtp->Hello($hello);
  724. }
  725. $connection = true;
  726. if ($this->SMTPAuth) {
  727. if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
  728. throw new phpmailerException($this->Lang('authenticate'));
  729. }
  730. }
  731. }
  732. $index++;
  733. if (!$connection) {
  734. throw new phpmailerException($this->Lang('connect_host'));
  735. }
  736. }
  737. } catch (phpmailerException $e) {
  738. $this->smtp->Reset();
  739. throw $e;
  740. }
  741. return true;
  742. }
  743. /**
  744. * Closes the active SMTP session if one exists.
  745. * @return void
  746. */
  747. public function SmtpClose() {
  748. if(!is_null($this->smtp)) {
  749. if($this->smtp->Connected()) {
  750. $this->smtp->Quit();
  751. $this->smtp->Close();
  752. }
  753. }
  754. }
  755. /**
  756. * Sets the language for all class error messages.
  757. * Returns false if it cannot load the language file. The default language is English.
  758. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  759. * @param string $lang_path Path to the language file directory
  760. * @access public
  761. */
  762. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  763. //Define full set of translatable strings
  764. $PHPMAILER_LANG = array(
  765. 'provide_address' => 'You must provide at least one recipient email address.',
  766. 'mailer_not_supported' => ' mailer is not supported.',
  767. 'execute' => 'Could not execute: ',
  768. 'instantiate' => 'Could not instantiate mail function.',
  769. 'authenticate' => 'SMTP Error: Could not authenticate.',
  770. 'from_failed' => 'The following From address failed: ',
  771. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  772. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  773. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  774. 'file_access' => 'Could not access file: ',
  775. 'file_open' => 'File Error: Could not open file: ',
  776. 'encoding' => 'Unknown encoding: ',
  777. 'signing' => 'Signing Error: ',
  778. 'smtp_error' => 'SMTP server error: ',
  779. 'empty_message' => 'Message body empty',
  780. 'invalid_address' => 'Invalid address',
  781. 'variable_set' => 'Cannot set or reset variable: '
  782. );
  783. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  784. $l = true;
  785. if ($langcode != 'en') { //There is no English translation file
  786. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  787. }
  788. $this->language = $PHPMAILER_LANG;
  789. return ($l == true); //Returns false if language not found
  790. }
  791. /**
  792. * Return the current array of language strings
  793. * @return array
  794. */
  795. public function GetTranslations() {
  796. return $this->language;
  797. }
  798. /
  799. // METHODS, MESSAGE CREATION
  800. /
  801. /**
  802. * Creates recipient headers.
  803. * @access public
  804. * @return string
  805. */
  806. public function AddrAppend($type, $addr) {
  807. $addr_str = $type . ': ';
  808. $addresses = array();
  809. foreach ($addr as $a) {
  810. $addresses[] = $this->AddrFormat($a);
  811. }
  812. $addr_str .= implode(', ', $addresses);
  813. $addr_str .= $this->LE;
  814. return $addr_str;
  815. }
  816. /**
  817. * Formats an address correctly.
  818. * @access public
  819. * @return string
  820. */
  821. public function AddrFormat($addr) {
  822. if (empty($addr[1])) {
  823. return $this->SecureHeader($addr[0]);
  824. } else {
  825. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  826. }
  827. }
  828. /**
  829. * Wraps message for use with mailers that do not
  830. * automatically perform wrapping and for quoted-printable.
  831. * Original written by philippe.
  832. * @param string $message The message to wrap
  833. * @param integer $length The line length to wrap to
  834. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  835. * @access public
  836. * @return string
  837. */
  838. public function WrapText($message, $length, $qp_mode = false) {
  839. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  840. // If utf-8 encoding is used, we will need to make sure we don't
  841. // split multibyte characters when we wrap
  842. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  843. $message = $this->FixEOL($message);
  844. if (substr($message, -1) == $this->LE) {
  845. $message = substr($message, 0, -1);
  846. }
  847. $line = explode($this->LE, $message);
  848. $message = '';
  849. for ($i=0 ;$i < count($line); $i++) {
  850. $line_part = explode(' ', $line[$i]);
  851. $buf = '';
  852. for ($e = 0; $e<count($line_part); $e++) {
  853. $word = $line_part[$e];
  854. if ($qp_mode and (strlen($word) > $length)) {
  855. $space_left = $length - strlen($buf) - 1;
  856. if ($e != 0) {
  857. if ($space_left > 20) {
  858. $len = $space_left;
  859. if ($is_utf8) {
  860. $len = $this->UTF8CharBoundary($word, $len);
  861. } elseif (substr($word, $len - 1, 1) == "=") {
  862. $len--;
  863. } elseif (substr($word, $len - 2, 1) == "=") {
  864. $len -= 2;
  865. }
  866. $part = substr($word, 0, $len);
  867. $word = substr($word, $len);
  868. $buf .= ' ' . $part;
  869. $message .= $buf . sprintf("=%s", $this->LE);
  870. } else {
  871. $message .= $buf . $soft_break;
  872. }
  873. $buf = '';
  874. }
  875. while (strlen($word) > 0) {
  876. $len = $length;
  877. if ($is_utf8) {
  878. $len = $this->UTF8CharBoundary($word, $len);
  879. } elseif (substr($word, $len - 1, 1) == "=") {
  880. $len--;
  881. } elseif (substr($word, $len - 2, 1) == "=") {
  882. $len -= 2;
  883. }
  884. $part = substr($word, 0, $len);
  885. $word = substr($word, $len);
  886. if (strlen($word) > 0) {
  887. $message .= $part . sprintf("=%s", $this->LE);
  888. } else {
  889. $buf = $part;
  890. }
  891. }
  892. } else {
  893. $buf_o = $buf;
  894. $buf .= ($e == 0) ? $word : (' ' . $word);
  895. if (strlen($buf) > $length and $buf_o != '') {
  896. $message .= $buf_o . $soft_break;
  897. $buf = $word;
  898. }
  899. }
  900. }
  901. $message .= $buf . $this->LE;
  902. }
  903. return $message;
  904. }
  905. /**
  906. * Finds last character boundary prior to maxLength in a utf-8
  907. * quoted (printable) encoded string.
  908. * Original written by Colin Brown.
  909. * @access public
  910. * @param string $encodedText utf-8 QP text
  911. * @param int $maxLength find last character boundary prior to this length
  912. * @return int
  913. */
  914. public function UTF8CharBoundary($encodedText, $maxLength) {
  915. $foundSplitPos = false;
  916. $lookBack = 3;
  917. while (!$foundSplitPos) {
  918. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  919. $encodedCharPos = strpos($lastChunk, "=");
  920. if ($encodedCharPos !== false) {
  921. // Found start of encoded character byte within $lookBack block.
  922. // Check the encoded byte value (the 2 chars after the '=')
  923. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  924. $dec = hexdec($hex);
  925. if ($dec < 128) { // Single byte character.
  926. // If the encoded char was found at pos 0, it will fit
  927. // otherwise reduce maxLength to start of the encoded char
  928. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  929. $maxLength - ($lookBack - $encodedCharPos);
  930. $foundSplitPos = true;
  931. } elseif ($dec >= 192) { // First byte of a multi byte character
  932. // Reduce maxLength to split at start of character
  933. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  934. $foundSplitPos = true;
  935. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  936. $lookBack += 3;
  937. }
  938. } else {
  939. // No encoded character found
  940. $foundSplitPos = true;
  941. }
  942. }
  943. return $maxLength;
  944. }
  945. /**
  946. * Set the body wrapping.
  947. * @access public
  948. * @return void
  949. */
  950. public function SetWordWrap() {
  951. if($this->WordWrap < 1) {
  952. return;
  953. }
  954. switch($this->message_type) {
  955. case 'alt':
  956. case 'alt_attachments':
  957. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  958. break;
  959. default:
  960. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  961. break;
  962. }
  963. }
  964. /**
  965. * Assembles message header.
  966. * @access public
  967. * @return string The assembled header
  968. */
  969. public function CreateHeader() {
  970. $result = '';
  971. // Set the boundaries
  972. $uniq_id = md5(uniqid(time()));
  973. $this->boundary[1] = 'b1_' . $uniq_id;
  974. $this->boundary[2] = 'b2_' . $uniq_id;
  975. $result .= $this->HeaderLine('Date', self::RFCDate());
  976. if($this->Sender == '') {
  977. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  978. } else {
  979. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  980. }
  981. // To be created automatically by mail()
  982. if($this->Mailer != 'mail') {
  983. if ($this->SingleTo === true) {
  984. foreach($this->to as $t) {
  985. $this->SingleToArray[] = $this->AddrFormat($t);
  986. }
  987. } else {
  988. if(count($this->to) > 0) {
  989. $result .= $this->AddrAppend('To', $this->to);
  990. } elseif (count($this->cc) == 0) {
  991. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  992. }
  993. }
  994. }
  995. $from = array();
  996. $from[0][0] = trim($this->From);
  997. $from[0][1] = $this->FromName;
  998. $result .= $this->AddrAppend('From', $from);
  999. // sendmail and mail() extract Cc from the header before sending
  1000. if(count($this->cc) > 0) {
  1001. $result .= $this->AddrAppend('Cc', $this->cc);
  1002. }
  1003. // sendmail and mail() extract Bcc from the header before sending
  1004. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  1005. $result .= $this->AddrAppend('Bcc', $this->bcc);
  1006. }
  1007. if(count($this->ReplyTo) > 0) {
  1008. $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
  1009. }
  1010. // mail() sets the subject itself
  1011. if($this->Mailer != 'mail') {
  1012. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  1013. }
  1014. if($this->MessageID != '') {
  1015. $result .= $this->HeaderLine('Message-ID',$this->MessageID);
  1016. } else {
  1017. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  1018. }
  1019. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  1020. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)');
  1021. if($this->ConfirmReadingTo != '') {
  1022. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1023. }
  1024. // Add custom headers
  1025. for($index = 0; $index < count($this->CustomHeader); $index++) {
  1026. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  1027. }
  1028. if (!$this->sign_key_file) {
  1029. $result .= $this->HeaderLine('MIME-Version', '1.0');
  1030. $result .= $this->GetMailMIME();
  1031. }
  1032. return $result;
  1033. }
  1034. /**
  1035. * Returns the message MIME.
  1036. * @access public
  1037. * @return string
  1038. */
  1039. public function GetMailMIME() {
  1040. $result = '';
  1041. switch($this->message_type) {
  1042. case 'plain':
  1043. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  1044. $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
  1045. break;
  1046. case 'attachments':
  1047. case 'alt_attachments':
  1048. if($this->InlineImageExists()){
  1049. $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
  1050. } else {
  1051. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  1052. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1053. }
  1054. break;
  1055. case 'alt':
  1056. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1057. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1058. break;
  1059. }
  1060. if($this->Mailer != 'mail') {
  1061. $result .= $this->LE.$this->LE;
  1062. }
  1063. return $result;
  1064. }
  1065. /**
  1066. * Assembles the message body. Returns an empty string on failure.
  1067. * @access public
  1068. * @return string The assembled message body
  1069. */
  1070. public function CreateBody() {
  1071. $body = '';
  1072. if ($this->sign_key_file) {
  1073. $body .= $this->GetMailMIME();
  1074. }
  1075. $this->SetWordWrap();
  1076. switch($this->message_type) {
  1077. case 'alt':
  1078. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1079. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1080. $body .= $this->LE.$this->LE;
  1081. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  1082. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1083. $body .= $this->LE.$this->LE;
  1084. $body .= $this->EndBoundary($this->boundary[1]);
  1085. break;
  1086. case 'plain':
  1087. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1088. break;
  1089. case 'attachments':
  1090. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1091. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1092. $body .= $this->LE;
  1093. $body .= $this->AttachAll();
  1094. break;
  1095. case 'alt_attachments':
  1096. $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
  1097. $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
  1098. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
  1099. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1100. $body .= $this->LE.$this->LE;
  1101. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
  1102. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1103. $body .= $this->LE.$this->LE;
  1104. $body .= $this->EndBoundary($this->boundary[2]);
  1105. $body .= $this->AttachAll();
  1106. break;
  1107. }
  1108. if ($this->IsError()) {
  1109. $body = '';
  1110. } elseif ($this->sign_key_file) {
  1111. try {
  1112. $file = tempnam('', 'mail');
  1113. file_put_contents($file, $body); //TODO check this worked
  1114. $signed = tempnam("", "signed");
  1115. if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
  1116. @unlink($file);
  1117. @unlink($signed);
  1118. $body = file_get_contents($signed);
  1119. } else {
  1120. @unlink($file);
  1121. @unlink($signed);
  1122. throw new phpmailerException($this->Lang("signing").openssl_error_string());
  1123. }
  1124. } catch (phpmailerException $e) {
  1125. $body = '';
  1126. if ($this->exceptions) {
  1127. throw $e;
  1128. }
  1129. }
  1130. }
  1131. return $body;
  1132. }
  1133. /**
  1134. * Returns the start of a message boundary.
  1135. * @access private
  1136. */
  1137. private function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1138. $result = '';
  1139. if($charSet == '') {
  1140. $charSet = $this->CharSet;
  1141. }
  1142. if($contentType == '') {
  1143. $contentType = $this->ContentType;
  1144. }
  1145. if($encoding == '') {
  1146. $encoding = $this->Encoding;
  1147. }
  1148. $result .= $this->TextLine('--' . $boundary);
  1149. $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
  1150. $result .= $this->LE;
  1151. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1152. $result .= $this->LE;
  1153. return $result;
  1154. }
  1155. /**
  1156. * Returns the end of a message boundary.
  1157. * @access private
  1158. */
  1159. private function EndBoundary($boundary) {
  1160. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1161. }
  1162. /**
  1163. * Sets the message type.
  1164. * @access private
  1165. * @return void
  1166. */
  1167. private function SetMessageType() {
  1168. if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
  1169. $this->message_type = 'plain';
  1170. } else {
  1171. if(count($this->attachment) > 0) {
  1172. $this->message_type = 'attachments';
  1173. }
  1174. if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
  1175. $this->message_type = 'alt';
  1176. }
  1177. if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
  1178. $this->message_type = 'alt_attachments';
  1179. }
  1180. }
  1181. }
  1182. /**
  1183. * Returns a formatted header line.
  1184. * @access public
  1185. * @return string
  1186. */
  1187. public function HeaderLine($name, $value) {
  1188. return $name . ': ' . $value . $this->LE;
  1189. }
  1190. /**
  1191. * Returns a formatted mail line.
  1192. * @access public
  1193. * @return string
  1194. */
  1195. public function TextLine($value) {
  1196. return $value . $this->LE;
  1197. }
  1198. /
  1199. // CLASS METHODS, ATTACHMENTS
  1200. /
  1201. /**
  1202. * Adds an attachment from a path on the filesystem.
  1203. * Returns false if the file could not be found
  1204. * or accessed.
  1205. * @param string $path Path to the attachment.
  1206. * @param string $name Overrides the attachment name.
  1207. * @param string $encoding File encoding (see $Encoding).
  1208. * @param string $type File extension (MIME) type.
  1209. * @return bool
  1210. */
  1211. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1212. try {
  1213. if ( !@is_file($path) ) {
  1214. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1215. }
  1216. $filename = basename($path);
  1217. if ( $name == '' ) {
  1218. $name = $filename;
  1219. }
  1220. $this->attachment[] = array(
  1221. 0 => $path,
  1222. 1 => $filename,
  1223. 2 => $name,
  1224. 3 => $encoding,
  1225. 4 => $type,
  1226. 5 => false, // isStringAttachment
  1227. 6 => 'attachment',
  1228. 7 => 0
  1229. );
  1230. } catch (phpmailerException $e) {
  1231. $this->SetError($e->getMessage());
  1232. if ($this->exceptions) {
  1233. throw $e;
  1234. }
  1235. echo $e->getMessage()."\n";
  1236. if ( $e->getCode() == self::STOP_CRITICAL ) {
  1237. return false;
  1238. }
  1239. }
  1240. return true;
  1241. }
  1242. /**
  1243. * Return the current array of attachments
  1244. * @return array
  1245. */
  1246. public function GetAttachments() {
  1247. return $this->attachment;
  1248. }
  1249. /**
  1250. * Attaches all fs, string, and binary attachments to the message.
  1251. * Returns an empty string on failure.
  1252. * @access private
  1253. * @return string
  1254. */
  1255. private function AttachAll() {
  1256. // Return text of body
  1257. $mime = array();
  1258. $cidUniq = array();
  1259. $incl = array();
  1260. // Add all attachments
  1261. foreach ($this->attachment as $attachment) {
  1262. // Check for string attachment
  1263. $bString = $attachment[5];
  1264. if ($bString) {
  1265. $string = $attachment[0];
  1266. } else {
  1267. $path = $attachment[0];
  1268. }
  1269. if (in_array($attachment[0], $incl)) { continue; }
  1270. $filename = $attachment[1];
  1271. $name = $attachment[2];
  1272. $encoding = $attachment[3];
  1273. $type = $attachment[4];
  1274. $disposition = $attachment[6];
  1275. $cid = $attachment[7];
  1276. $incl[] = $attachment[0];
  1277. if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
  1278. $cidUniq[$cid] = true;
  1279. $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
  1280. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1281. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1282. if($disposition == 'inline') {
  1283. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1284. }
  1285. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1286. // Encode as string attachment
  1287. if($bString) {
  1288. $mime[] = $this->EncodeString($string, $encoding);
  1289. if($this->IsError()) {
  1290. return '';
  1291. }
  1292. $mime[] = $this->LE.$this->LE;
  1293. } else {
  1294. $mime[] = $this->EncodeFile($path, $encoding);
  1295. if($this->IsError()) {
  1296. return '';
  1297. }
  1298. $mime[] = $this->LE.$this->LE;
  1299. }
  1300. }
  1301. $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
  1302. return join('', $mime);
  1303. }
  1304. /**
  1305. * Encodes attachment in requested format.
  1306. * Returns an empty string on failure.
  1307. * @param string $path The full path to the file
  1308. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1309. * @see EncodeFile()
  1310. * @access private
  1311. * @return string
  1312. */
  1313. private function EncodeFile($path, $encoding = 'base64') {
  1314. try {
  1315. if (!is_readable($path)) {
  1316. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1317. }
  1318. if (function_exists('get_magic_quotes')) {
  1319. function get_magic_quotes() {
  1320. return false;
  1321. }
  1322. }
  1323. if (PHP_VERSION < 6) {
  1324. $magic_quotes = get_magic_quotes_runtime();
  1325. set_magic_quotes_runtime(0);
  1326. }
  1327. $file_buffer = file_get_contents($path);
  1328. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1329. if (PHP_VERSION < 6) { set_magic_quotes_runtime($magic_quotes); }
  1330. return $file_buffer;
  1331. } catch (Exception $e) {
  1332. $this->SetError($e->getMessage());
  1333. return '';
  1334. }
  1335. }
  1336. /**
  1337. * Encodes string to requested format.
  1338. * Returns an empty string on failure.
  1339. * @param string $str The text to encode
  1340. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1341. * @access public
  1342. * @return string
  1343. */
  1344. public function EncodeString ($str, $encoding = 'base64') {
  1345. $encoded = '';
  1346. switch(strtolower($encoding)) {
  1347. case 'base64':
  1348. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1349. break;
  1350. case '7bit':
  1351. case '8bit':
  1352. $encoded = $this->FixEOL($str);
  1353. //Make sure it ends with a line break
  1354. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1355. $encoded .= $this->LE;
  1356. break;
  1357. case 'binary':
  1358. $encoded = $str;
  1359. break;
  1360. case 'quoted-printable':
  1361. $encoded = $this->EncodeQP($str);
  1362. break;
  1363. default:
  1364. $this->SetError($this->Lang('encoding') . $encoding);
  1365. break;
  1366. }
  1367. return $encoded;
  1368. }
  1369. /**
  1370. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1371. * @access public
  1372. * @return string
  1373. */
  1374. public function EncodeHeader($str, $position = 'text') {
  1375. $x = 0;
  1376. switch (strtolower($position)) {
  1377. case 'phrase':
  1378. if (!preg_match('/[\200-\377]/', $str)) {
  1379. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1380. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1381. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1382. return ($encoded);
  1383. } else {
  1384. return ("\"$encoded\"");
  1385. }
  1386. }
  1387. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1388. break;
  1389. case 'comment':
  1390. $x = preg_match_all('/[()"]/', $str, $matches);
  1391. // Fall-through
  1392. case 'text':
  1393. default:
  1394. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1395. break;
  1396. }
  1397. if ($x == 0) {
  1398. return ($str);
  1399. }
  1400. $maxlen = 75 - 7 - strlen($this->CharSet);
  1401. // Try to select the encoding which should produce the shortest output
  1402. if (strlen($str)/3 < $x) {
  1403. $encoding = 'B';
  1404. if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1405. // Use a custom function which correctly encodes and wraps long
  1406. // multibyte strings without breaking lines within a character
  1407. $encoded = $this->Base64EncodeWrapMB($str);
  1408. } else {
  1409. $encoded = base64_encode($str);
  1410. $maxlen -= $maxlen % 4;
  1411. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1412. }
  1413. } else {
  1414. $encoding = 'Q';
  1415. $encoded = $this->EncodeQ($str, $position);
  1416. $encoded = $this->WrapText($encoded, $maxlen, true);
  1417. $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
  1418. }
  1419. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1420. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1421. return $encoded;
  1422. }
  1423. /**
  1424. * Checks if a string contains multibyte characters.
  1425. * @access public
  1426. * @param string $str multi-byte text to wrap encode
  1427. * @return bool
  1428. */
  1429. public function HasMultiBytes($str) {
  1430. if (function_exists('mb_strlen')) {
  1431. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1432. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1433. return false;
  1434. }
  1435. }
  1436. /**
  1437. * Correctly encodes and wraps long multibyte strings for mail headers
  1438. * without breaking lines within a character.
  1439. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1440. * @access public
  1441. * @param string $str multi-byte text to wrap encode
  1442. * @return string
  1443. */
  1444. public function Base64EncodeWrapMB($str) {
  1445. $start = "=?".$this->CharSet."?B?";
  1446. $end = "?=";
  1447. $encoded = "";
  1448. $mb_length = mb_strlen($str, $this->CharSet);
  1449. // Each line must have length <= 75, including $start and $end
  1450. $length = 75 - strlen($start) - strlen($end);
  1451. // Average multi-byte ratio
  1452. $ratio = $mb_length / strlen($str);
  1453. // Base64 has a 4:3 ratio
  1454. $offset = $avgLength = floor($length * $ratio * .75);
  1455. for ($i = 0; $i < $mb_length; $i += $offset) {
  1456. $lookBack = 0;
  1457. do {
  1458. $offset = $avgLength - $lookBack;
  1459. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1460. $chunk = base64_encode($chunk);
  1461. $lookBack++;
  1462. }
  1463. while (strlen($chunk) > $length);
  1464. $encoded .= $chunk . $this->LE;
  1465. }
  1466. // Chomp the last linefeed
  1467. $encoded = substr($encoded, 0, -strlen($this->LE));
  1468. return $encoded;
  1469. }
  1470. /**
  1471. * Encode string to quoted-printable.
  1472. * Only uses standard PHP, slow, but will always work
  1473. * @access public
  1474. * @param string $string the text to encode
  1475. * @param integer $line_max Number of chars allowed on a line before wrapping
  1476. * @return string
  1477. */
  1478. public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
  1479. $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
  1480. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1481. $eol = "\r\n";
  1482. $escape = '=';
  1483. $output = '';
  1484. while( list(, $line) = each($lines) ) {
  1485. $linlen = strlen($line);
  1486. $newline = '';
  1487. for($i = 0; $i < $linlen; $i++) {
  1488. $c = substr( $line, $i, 1 );
  1489. $dec = ord( $c );
  1490. if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
  1491. $c = '=2E';
  1492. }
  1493. if ( $dec == 32 ) {
  1494. if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
  1495. $c = '=20';
  1496. } else if ( $space_conv ) {
  1497. $c = '=20';
  1498. }
  1499. } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
  1500. $h2 = floor($dec/16);
  1501. $h1 = floor($dec%16);
  1502. $c = $escape.$hex[$h2].$hex[$h1];
  1503. }
  1504. if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
  1505. $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
  1506. $newline = '';
  1507. // check if newline first character will be point or not
  1508. if ( $dec == 46 ) {
  1509. $c = '=2E';
  1510. }
  1511. }
  1512. $newline .= $c;
  1513. } // end of for
  1514. $output .= $newline.$eol;
  1515. } // end of while
  1516. return $output;
  1517. }
  1518. /**
  1519. * Encode string to RFC2045 (6.7) quoted-printable format
  1520. * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
  1521. * Also results in same content as you started with after decoding
  1522. * @see EncodeQPphp()
  1523. * @access public
  1524. * @param string $string the text to encode
  1525. * @param integer $line_max Number of chars allowed on a line before wrapping
  1526. * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
  1527. * @return string
  1528. * @author Marcus Bointon
  1529. */
  1530. public function EncodeQP($string, $line_max = 76, $space_conv = false) {
  1531. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  1532. return quoted_printable_encode($string);
  1533. }
  1534. $filters = stream_get_filters();
  1535. if (!in_array('convert.*', $filters)) { //Got convert stream filter?
  1536. return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
  1537. }
  1538. $fp = fopen('php://temp/', 'r+');
  1539. $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
  1540. $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
  1541. $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
  1542. fputs($fp, $string);
  1543. rewind($fp);
  1544. $out = stream_get_contents($fp);
  1545. stream_filter_remove($s);
  1546. $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
  1547. fclose($fp);
  1548. return $out;
  1549. }
  1550. /**
  1551. * Encode string to q encoding.
  1552. * @link http://tools.ietf.org/html/rfc2047
  1553. * @param string $str the text to encode
  1554. * @param string $position Where the text is going to be used, see the RFC for what that means
  1555. * @access public
  1556. * @return string
  1557. */
  1558. public function EncodeQ ($str, $position = 'text') {
  1559. // There should not be any EOL in the string
  1560. $encoded = preg_replace('/[\r\n]*/', '', $str);
  1561. switch (strtolower($position)) {
  1562. case 'phrase':
  1563. $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1564. break;
  1565. case 'comment':
  1566. $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1567. case 'text':
  1568. default:
  1569. // Replace every high ascii, control =, ? and _ characters
  1570. //TODO using /e (equivalent to eval()) is probably not a good idea
  1571. $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
  1572. "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1573. break;
  1574. }
  1575. // Replace every spaces to _ (more readable than =20)
  1576. $encoded = str_replace(' ', '_', $encoded);
  1577. return $encoded;
  1578. }
  1579. /**
  1580. * Adds a string or binary attachment (non-filesystem) to the list.
  1581. * This method can be used to attach ascii or binary data,
  1582. * such as a BLOB record from a database.
  1583. * @param string $string String attachment data.
  1584. * @param string $filename Name of the attachment.
  1585. * @param string $encoding File encoding (see $Encoding).
  1586. * @param string $type File extension (MIME) type.
  1587. * @return void
  1588. */
  1589. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
  1590. // Append to $attachment array
  1591. $this->attachment[] = array(
  1592. 0 => $string,
  1593. 1 => $filename,
  1594. 2 => basename($filename),
  1595. 3 => $encoding,
  1596. 4 => $type,
  1597. 5 => true, // isStringAttachment
  1598. 6 => 'attachment',
  1599. 7 => 0
  1600. );
  1601. }
  1602. /**
  1603. * Adds an embedded attachment. This can include images, sounds, and
  1604. * just about any other document. Make sure to set the $type to an
  1605. * image type. For JPEG images use "image/jpeg" and for GIF images
  1606. * use "image/gif".
  1607. * @param string $path Path to the attachment.
  1608. * @param string $cid Content ID of the attachment. Use this to identify
  1609. * the Id for accessing the image in an HTML form.
  1610. * @param string $name Overrides the attachment name.
  1611. * @param string $encoding File encoding (see $Encoding).
  1612. * @param string $type File extension (MIME) type.
  1613. * @return bool
  1614. */
  1615. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1616. if ( !@is_file($path) ) {
  1617. $this->SetError($this->Lang('file_access') . $path);
  1618. return false;
  1619. }
  1620. $filename = basename($path);
  1621. if ( $name == '' ) {
  1622. $name = $filename;
  1623. }
  1624. // Append to $attachment array
  1625. $this->attachment[] = array(
  1626. 0 => $path,
  1627. 1 => $filename,
  1628. 2 => $name,
  1629. 3 => $encoding,
  1630. 4 => $type,
  1631. 5 => false, // isStringAttachment
  1632. 6 => 'inline',
  1633. 7 => $cid
  1634. );
  1635. return true;
  1636. }
  1637. /**
  1638. * Returns true if an inline attachment is present.
  1639. * @access public
  1640. * @return bool
  1641. */
  1642. public function InlineImageExists() {
  1643. foreach($this->attachment as $attachment) {
  1644. if ($attachment[6] == 'inline') {
  1645. return true;
  1646. }
  1647. }
  1648. return false;
  1649. }
  1650. /
  1651. // CLASS METHODS, MESSAGE RESET
  1652. /
  1653. /**
  1654. * Clears all recipients assigned in the TO array. Returns void.
  1655. * @return void
  1656. */
  1657. public function ClearAddresses() {
  1658. foreach($this->to as $to) {
  1659. unset($this->all_recipients[strtolower($to[0])]);
  1660. }
  1661. $this->to = array();
  1662. }
  1663. /**
  1664. * Clears all recipients assigned in the CC array. Returns void.
  1665. * @return void
  1666. */
  1667. public function ClearCCs() {
  1668. foreach($this->cc as $cc) {
  1669. unset($this->all_recipients[strtolower($cc[0])]);
  1670. }
  1671. $this->cc = array();
  1672. }
  1673. /**
  1674. * Clears all recipients assigned in the BCC array. Returns void.
  1675. * @return void
  1676. */
  1677. public function ClearBCCs() {
  1678. foreach($this->bcc as $bcc) {
  1679. unset($this->all_recipients[strtolower($bcc[0])]);
  1680. }
  1681. $this->bcc = array();
  1682. }
  1683. /**
  1684. * Clears all recipients assigned in the ReplyTo array. Returns void.
  1685. * @return void
  1686. */
  1687. public function ClearReplyTos() {
  1688. $this->ReplyTo = array();
  1689. }
  1690. /**
  1691. * Clears all recipients assigned in the TO, CC and BCC
  1692. * array. Returns void.
  1693. * @return void
  1694. */
  1695. public function ClearAllRecipients() {
  1696. $this->to = array();
  1697. $this->cc = array();
  1698. $this->bcc = array();
  1699. $this->all_recipients = array();
  1700. }
  1701. /**
  1702. * Clears all previously set filesystem, string, and binary
  1703. * attachments. Returns void.
  1704. * @return void
  1705. */
  1706. public function ClearAttachments() {
  1707. $this->attachment = array();
  1708. }
  1709. /**
  1710. * Clears all custom headers. Returns void.
  1711. * @return void
  1712. */
  1713. public function ClearCustomHeaders() {
  1714. $this->CustomHeader = array();
  1715. }
  1716. /
  1717. // CLASS METHODS, MISCELLANEOUS
  1718. /
  1719. /**
  1720. * Adds the error message to the error container.
  1721. * @access protected
  1722. * @return void
  1723. */
  1724. protected function SetError($msg) {
  1725. $this->error_count++;
  1726. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  1727. $lasterror = $this->smtp->getError();
  1728. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  1729. $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  1730. }
  1731. }
  1732. $this->ErrorInfo = $msg;
  1733. }
  1734. /**
  1735. * Returns the proper RFC 822 formatted date.
  1736. * @access public
  1737. * @return string
  1738. * @static
  1739. */
  1740. public static function RFCDate() {
  1741. $tz = date('Z');
  1742. $tzs = ($tz < 0) ? '-' : '+';
  1743. $tz = abs($tz);
  1744. $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
  1745. $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
  1746. return $result;
  1747. }
  1748. /**
  1749. * Returns the server hostname or 'localhost.localdomain' if unknown.
  1750. * @access private
  1751. * @return string
  1752. */
  1753. private function ServerHostname() {
  1754. if (!empty($this->Hostname)) {
  1755. $result = $this->Hostname;
  1756. } elseif (isset($_SERVER['SERVER_NAME'])) {
  1757. $result = $_SERVER['SERVER_NAME'];
  1758. } else {
  1759. $result = 'localhost.localdomain';
  1760. }
  1761. return $result;
  1762. }
  1763. /**
  1764. * Returns a message in the appropriate language.
  1765. * @access private
  1766. * @return string
  1767. */
  1768. private function Lang($key) {
  1769. if(count($this->language) < 1) {
  1770. $this->SetLanguage('en'); // set the default language
  1771. }
  1772. if(isset($this->language[$key])) {
  1773. return $this->language[$key];
  1774. } else {
  1775. return 'Language string failed to load: ' . $key;
  1776. }
  1777. }
  1778. /**
  1779. * Returns true if an error occurred.
  1780. * @access public
  1781. * @return bool
  1782. */
  1783. public function IsError() {
  1784. return ($this->error_count > 0);
  1785. }
  1786. /**
  1787. * Changes every end of line from CR or LF to CRLF.
  1788. * @access private
  1789. * @return string
  1790. */
  1791. private function FixEOL($str) {
  1792. $str = str_replace("\r\n", "\n", $str);
  1793. $str = str_replace("\r", "\n", $str);
  1794. $str = str_replace("\n", $this->LE, $str);
  1795. return $str;
  1796. }
  1797. /**
  1798. * Adds a custom header.
  1799. * @access public
  1800. * @return void
  1801. */
  1802. public function AddCustomHeader($custom_header) {
  1803. $this->CustomHeader[] = explode(':', $custom_header, 2);
  1804. }
  1805. /**
  1806. * Evaluates the message and returns modifications for inline images and backgrounds
  1807. * @access public
  1808. * @return $message
  1809. */
  1810. public function MsgHTML($message, $basedir = '') {
  1811. preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
  1812. if(isset($images[2])) {
  1813. foreach($images[2] as $i => $url) {
  1814. // do not change urls for absolute images (thanks to corvuscorax)
  1815. if (!preg_match('#^[A-z]+://#',$url)) {
  1816. $filename = basename($url);
  1817. $directory = dirname($url);
  1818. ($directory == '.')?$directory='':'';
  1819. $cid = 'cid:' . md5($filename);
  1820. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  1821. $mimeType = self::_mime_types($ext);
  1822. if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; }
  1823. if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; }
  1824. if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) {
  1825. $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
  1826. }
  1827. }
  1828. }
  1829. }
  1830. $this->IsHTML(true);
  1831. $this->Body = $message;
  1832. $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
  1833. if (!empty($textMsg) && empty($this->AltBody)) {
  1834. $this->AltBody = html_entity_decode($textMsg);
  1835. }
  1836. if (empty($this->AltBody)) {
  1837. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
  1838. }
  1839. }
  1840. /**
  1841. * Gets the MIME type of the embedded or inline image
  1842. * @param string File extension
  1843. * @access public
  1844. * @return string MIME type of ext
  1845. * @static
  1846. */
  1847. public static function _mime_types($ext = '') {
  1848. $mimes = array(
  1849. 'hqx' => 'application/mac-binhex40',
  1850. 'cpt' => 'application/mac-compactpro',
  1851. 'doc' => 'application/msword',
  1852. 'bin' => 'application/macbinary',
  1853. 'dms' => 'application/octet-stream',
  1854. 'lha' => 'application/octet-stream',
  1855. 'lzh' => 'application/octet-stream',
  1856. 'exe' => 'application/octet-stream',
  1857. 'class' => 'application/octet-stream',
  1858. 'psd' => 'application/octet-stream',
  1859. 'so' => 'application/octet-stream',
  1860. 'sea' => 'application/octet-stream',
  1861. 'dll' => 'application/octet-stream',
  1862. 'oda' => 'application/oda',
  1863. 'pdf' => 'application/pdf',
  1864. 'ai' => 'application/postscript',
  1865. 'eps' => 'application/postscript',
  1866. 'ps' => 'application/postscript',
  1867. 'smi' => 'application/smil',
  1868. 'smil' => 'application/smil',
  1869. 'mif' => 'application/vnd.mif',
  1870. 'xls' => 'application/vnd.ms-excel',
  1871. 'ppt' => 'application/vnd.ms-powerpoint',
  1872. 'wbxml' => 'application/vnd.wap.wbxml',
  1873. 'wmlc' => 'application/vnd.wap.wmlc',
  1874. 'dcr' => 'application/x-director',
  1875. 'dir' => 'application/x-director',
  1876. 'dxr' => 'application/x-director',
  1877. 'dvi' => 'application/x-dvi',
  1878. 'gtar' => 'application/x-gtar',
  1879. 'php' => 'application/x-httpd-php',
  1880. 'php4' => 'application/x-httpd-php',
  1881. 'php3' => 'application/x-httpd-php',
  1882. 'phtml' => 'application/x-httpd-php',
  1883. 'phps' => 'application/x-httpd-php-source',
  1884. 'js' => 'application/x-javascript',
  1885. 'swf' => 'application/x-shockwave-flash',
  1886. 'sit' => 'application/x-stuffit',
  1887. 'tar' => 'application/x-tar',
  1888. 'tgz' => 'application/x-tar',
  1889. 'xhtml' => 'application/xhtml+xml',
  1890. 'xht' => 'application/xhtml+xml',
  1891. 'zip' => 'application/zip',
  1892. 'mid' => 'audio/midi',
  1893. 'midi' => 'audio/midi',
  1894. 'mpga' => 'audio/mpeg',
  1895. 'mp2' => 'audio/mpeg',
  1896. 'mp3' => 'audio/mpeg',
  1897. 'aif' => 'audio/x-aiff',
  1898. 'aiff' => 'audio/x-aiff',
  1899. 'aifc' => 'audio/x-aiff',
  1900. 'ram' => 'audio/x-pn-realaudio',
  1901. 'rm' => 'audio/x-pn-realaudio',
  1902. 'rpm' => 'audio/x-pn-realaudio-plugin',
  1903. 'ra' => 'audio/x-realaudio',
  1904. 'rv' => 'video/vnd.rn-realvideo',
  1905. 'wav' => 'audio/x-wav',
  1906. 'bmp' => 'image/bmp',
  1907. 'gif' => 'image/gif',
  1908. 'jpeg' => 'image/jpeg',
  1909. 'jpg' => 'image/jpeg',
  1910. 'jpe' => 'image/jpeg',
  1911. 'png' => 'image/png',
  1912. 'tiff' => 'image/tiff',
  1913. 'tif' => 'image/tiff',
  1914. 'css' => 'text/css',
  1915. 'html' => 'text/html',
  1916. 'htm' => 'text/html',
  1917. 'shtml' => 'text/html',
  1918. 'txt' => 'text/plain',
  1919. 'text' => 'text/plain',
  1920. 'log' => 'text/plain',
  1921. 'rtx' => 'text/richtext',
  1922. 'rtf' => 'text/rtf',
  1923. 'xml' => 'text/xml',
  1924. 'xsl' => 'text/xml',
  1925. 'mpeg' => 'video/mpeg',
  1926. 'mpg' => 'video/mpeg',
  1927. 'mpe' => 'video/mpeg',
  1928. 'qt' => 'video/quicktime',
  1929. 'mov' => 'video/quicktime',
  1930. 'avi' => 'video/x-msvideo',
  1931. 'movie' => 'video/x-sgi-movie',
  1932. 'doc' => 'application/msword',
  1933. 'word' => 'application/msword',
  1934. 'xl' => 'application/excel',
  1935. 'eml' => 'message/rfc822'
  1936. );
  1937. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  1938. }
  1939. /**
  1940. * Set (or reset) Class Objects (variables)
  1941. *
  1942. * Usage Example:
  1943. * $page->set('X-Priority', '3');
  1944. *
  1945. * @access public
  1946. * @param string $name Parameter Name
  1947. * @param mixed $value Parameter Value
  1948. * NOTE: will not work with arrays, there are no arrays to set/reset
  1949. * @todo Should this not be using __set() magic function?
  1950. */
  1951. public function set($name, $value = '') {
  1952. try {
  1953. if (isset($this->$name) ) {
  1954. $this->$name = $value;
  1955. } else {
  1956. throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
  1957. }
  1958. } catch (Exception $e) {
  1959. $this->SetError($e->getMessage());
  1960. if ($e->getCode() == self::STOP_CRITICAL) {
  1961. return false;
  1962. }
  1963. }
  1964. return true;
  1965. }
  1966. /**
  1967. * Strips newlines to prevent header injection.
  1968. * @access public
  1969. * @param string $str String
  1970. * @return string
  1971. */
  1972. public function SecureHeader($str) {
  1973. $str = str_replace("\r", '', $str);
  1974. $str = str_replace("\n", '', $str);
  1975. return trim($str);
  1976. }
  1977. /**
  1978. * Set the private key file and password to sign the message.
  1979. *
  1980. * @access public
  1981. * @param string $key_filename Parameter File Name
  1982. * @param string $key_pass Password for private key
  1983. */
  1984. public function Sign($cert_filename, $key_filename, $key_pass) {
  1985. $this->sign_cert_file = $cert_filename;
  1986. $this->sign_key_file = $key_filename;
  1987. $this->sign_key_pass = $key_pass;
  1988. }
  1989. /**
  1990. * Set the private key file and password to sign the message.
  1991. *
  1992. * @access public
  1993. * @param string $key_filename Parameter File Name
  1994. * @param string $key_pass Password for private key
  1995. */
  1996. public function DKIM_QP($txt) {
  1997. $tmp="";
  1998. $line="";
  1999. for ($i=0;$i<strlen($txt);$i++) {
  2000. $ord=ord($txt[$i]);
  2001. if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
  2002. $line.=$txt[$i];
  2003. } else {
  2004. $line.="=".sprintf("%02X",$ord);
  2005. }
  2006. }
  2007. return $line;
  2008. }
  2009. /**
  2010. * Generate DKIM signature
  2011. *
  2012. * @access public
  2013. * @param string $s Header
  2014. */
  2015. public function DKIM_Sign($s) {
  2016. $privKeyStr = file_get_contents($this->DKIM_private);
  2017. if ($this->DKIM_passphrase!='') {
  2018. $privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase);
  2019. } else {
  2020. $privKey = $privKeyStr;
  2021. }
  2022. if (openssl_sign($s, $signature, $privKey)) {
  2023. return base64_encode($signature);
  2024. }
  2025. }
  2026. /**
  2027. * Generate DKIM Canonicalization Header
  2028. *
  2029. * @access public
  2030. * @param string $s Header
  2031. */
  2032. public function DKIM_HeaderC($s) {
  2033. $s=preg_replace("/\r\n\s+/"," ",$s);
  2034. $lines=explode("\r\n",$s);
  2035. foreach ($lines as $key=>$line) {
  2036. list($heading,$value)=explode(":",$line,2);
  2037. $heading=strtolower($heading);
  2038. $value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces
  2039. $lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value
  2040. }
  2041. $s=implode("\r\n",$lines);
  2042. return $s;
  2043. }
  2044. /**
  2045. * Generate DKIM Canonicalization Body
  2046. *
  2047. * @access public
  2048. * @param string $body Message Body
  2049. */
  2050. public function DKIM_BodyC($body) {
  2051. if ($body == '') return "\r\n";
  2052. // stabilize line endings
  2053. $body=str_replace("\r\n","\n",$body);
  2054. $body=str_replace("\n","\r\n",$body);
  2055. // END stabilize line endings
  2056. while (substr($body,strlen($body)-4,4) == "\r\n\r\n") {
  2057. $body=substr($body,0,strlen($body)-2);
  2058. }
  2059. return $body;
  2060. }
  2061. /**
  2062. * Create the DKIM header, body, as new header
  2063. *
  2064. * @access public
  2065. * @param string $headers_line Header lines
  2066. * @param string $subject Subject
  2067. * @param string $body Body
  2068. */
  2069. public function DKIM_Add($headers_line,$subject,$body) {
  2070. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2071. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2072. $DKIMquery = 'dns/txt'; // Query method
  2073. $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2074. $subject_header = "Subject: $subject";
  2075. $headers = explode("\r\n",$headers_line);
  2076. foreach($headers as $header) {
  2077. if (strpos($header,'From:') === 0) {
  2078. $from_header=$header;
  2079. } elseif (strpos($header,'To:') === 0) {
  2080. $to_header=$header;
  2081. }
  2082. }
  2083. $from = str_replace('|','=7C',$this->DKIM_QP($from_header));
  2084. $to = str_replace('|','=7C',$this->DKIM_QP($to_header));
  2085. $subject = str_replace('|','=7C',$this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
  2086. $body = $this->DKIM_BodyC($body);
  2087. $DKIMlen = strlen($body) ; // Length of body
  2088. $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
  2089. $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
  2090. $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
  2091. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
  2092. "\th=From:To:Subject;\r\n".
  2093. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
  2094. "\tz=$from\r\n".
  2095. "\t|$to\r\n".
  2096. "\t|$subject;\r\n".
  2097. "\tbh=" . $DKIMb64 . ";\r\n".
  2098. "\tb=";
  2099. $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
  2100. $signed = $this->DKIM_Sign($toSign);
  2101. return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
  2102. }
  2103. protected function doCallback($isSent,$to,$cc,$bcc,$subject,$body) {
  2104. if (!empty($this->action_function) && function_exists($this->action_function)) {
  2105. $params = array($isSent,$to,$cc,$bcc,$subject,$body);
  2106. call_user_func_array($this->action_function,$params);
  2107. }
  2108. }
  2109. }
  2110. class phpmailerException extends Exception {
  2111. public function errorMessage() {
  2112. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2113. return $errorMsg;
  2114. }
  2115. }
  2116. ?>

二.class.smtp.php文件

  1. <?php
  2. /*~ class.smtp.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.1 |
  6. | Contact: via sourceforge.net support pages (also www.codeworxtech.com) |
  7. | Info: http://phpmailer.sourceforge.net |
  8. | Support: http://sourceforge.net/projects/phpmailer/ |
  9. | ------------------------------------------------------------------------- |
  10. | Admin: Andy Prevost (project admininistrator) |
  11. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  12. | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
  13. | Founder: Brent R. Matzelle (original founder) |
  14. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  15. | Copyright (c) 2001-2003, Brent R. Matzelle |
  16. | ------------------------------------------------------------------------- |
  17. | License: Distributed under the Lesser General Public License (LGPL) |
  18. | http://www.gnu.org/copyleft/lesser.html |
  19. | This program is distributed in the hope that it will be useful - WITHOUT |
  20. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  21. | FITNESS FOR A PARTICULAR PURPOSE. |
  22. | ------------------------------------------------------------------------- |
  23. | We offer a number of paid services (www.codeworxtech.com): |
  24. | - Web Hosting on highly optimized fast and secure servers |
  25. | - Technology Consulting |
  26. | - Oursourcing (highly qualified programmers and graphic designers) |
  27. '---------------------------------------------------------------------------'
  28. */
  29. /**
  30. * PHPMailer - PHP SMTP email transport class
  31. * NOTE: Designed for use with PHP version 5 and up
  32. * @package PHPMailer
  33. * @author Andy Prevost
  34. * @author Marcus Bointon
  35. * @copyright 2004 - 2008 Andy Prevost
  36. * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
  37. * @version $Id: class.smtp.php 444 2009-05-05 11:22:26Z coolbru $
  38. */
  39. /**
  40. * SMTP is rfc 821 compliant and implements all the rfc 821 SMTP
  41. * commands except TURN which will always return a not implemented
  42. * error. SMTP also provides some utility methods for sending mail
  43. * to an SMTP server.
  44. * original author: Chris Ryan
  45. */
  46. class SMTP {
  47. /**
  48. * SMTP server port
  49. * @var int
  50. */
  51. public $SMTP_PORT = 25;
  52. /**
  53. * SMTP reply line ending
  54. * @var string
  55. */
  56. public $CRLF = "\r\n";
  57. /**
  58. * Sets whether debugging is turned on
  59. * @var bool
  60. */
  61. public $do_debug; // the level of debug to perform
  62. /**
  63. * Sets VERP use on/off (default is off)
  64. * @var bool
  65. */
  66. public $do_verp = false;
  67. /
  68. // PROPERTIES, PRIVATE AND PROTECTED
  69. /
  70. private $smtp_conn; // the socket to the server
  71. private $error; // error if any on the last call
  72. private $helo_rply; // the reply the server sent to us for HELO
  73. /**
  74. * Initialize the class so that the data is in a known state.
  75. * @access public
  76. * @return void
  77. */
  78. public function __construct() {
  79. $this->smtp_conn = 0;
  80. $this->error = null;
  81. $this->helo_rply = null;
  82. $this->do_debug = 0;
  83. }
  84. /
  85. // CONNECTION FUNCTIONS
  86. /
  87. /**
  88. * Connect to the server specified on the port specified.
  89. * If the port is not specified use the default SMTP_PORT.
  90. * If tval is specified then a connection will try and be
  91. * established with the server for that number of seconds.
  92. * If tval is not specified the default is 30 seconds to
  93. * try on the connection.
  94. *
  95. * SMTP CODE SUCCESS: 220
  96. * SMTP CODE FAILURE: 421
  97. * @access public
  98. * @return bool
  99. */
  100. public function Connect($host, $port = 0, $tval = 30) {
  101. // set the error val to null so there is no confusion
  102. $this->error = null;
  103. // make sure we are __not__ connected
  104. if($this->connected()) {
  105. // already connected, generate error
  106. $this->error = array("error" => "Already connected to a server");
  107. return false;
  108. }
  109. if(empty($port)) {
  110. $port = $this->SMTP_PORT;
  111. }
  112. // connect to the smtp server
  113. $this->smtp_conn = @fsockopen($host, // the host of the server
  114. $port, // the port to use
  115. $errno, // error number if any
  116. $errstr, // error message if any
  117. $tval); // give up after ? secs
  118. // verify we connected properly
  119. if(empty($this->smtp_conn)) {
  120. $this->error = array("error" => "Failed to connect to server",
  121. "errno" => $errno,
  122. "errstr" => $errstr);
  123. if($this->do_debug >= 1) {
  124. echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />';
  125. }
  126. return false;
  127. }
  128. // SMTP server can take longer to respond, give longer timeout for first read
  129. // Windows does not have support for this timeout function
  130. if(substr(PHP_OS, 0, 3) != "WIN")
  131. socket_set_timeout($this->smtp_conn, $tval, 0);
  132. // get any announcement
  133. $announce = $this->get_lines();
  134. if($this->do_debug >= 2) {
  135. echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />';
  136. }
  137. return true;
  138. }
  139. /**
  140. * Initiate a TLS communication with the server.
  141. *
  142. * SMTP CODE 220 Ready to start TLS
  143. * SMTP CODE 501 Syntax error (no parameters allowed)
  144. * SMTP CODE 454 TLS not available due to temporary reason
  145. * @access public
  146. * @return bool success
  147. */
  148. public function StartTLS() {
  149. $this->error = null; # to avoid confusion
  150. if(!$this->connected()) {
  151. $this->error = array("error" => "Called StartTLS() without being connected");
  152. return false;
  153. }
  154. fputs($this->smtp_conn,"STARTTLS" . $this->CRLF);
  155. $rply = $this->get_lines();
  156. $code = substr($rply,0,3);
  157. if($this->do_debug >= 2) {
  158. echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
  159. }
  160. if($code != 220) {
  161. $this->error =
  162. array("error" => "STARTTLS not accepted from server",
  163. "smtp_code" => $code,
  164. "smtp_msg" => substr($rply,4));
  165. if($this->do_debug >= 1) {
  166. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  167. }
  168. return false;
  169. }
  170. // Begin encrypted connection
  171. if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
  172. return false;
  173. }
  174. return true;
  175. }
  176. /**
  177. * Performs SMTP authentication. Must be run after running the
  178. * Hello() method. Returns true if successfully authenticated.
  179. * @access public
  180. * @return bool
  181. */
  182. public function Authenticate($username, $password) {
  183. // Start authentication
  184. fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);
  185. $rply = $this->get_lines();
  186. $code = substr($rply,0,3);
  187. if($code != 334) {
  188. $this->error =
  189. array("error" => "AUTH not accepted from server",
  190. "smtp_code" => $code,
  191. "smtp_msg" => substr($rply,4));
  192. if($this->do_debug >= 1) {
  193. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  194. }
  195. return false;
  196. }
  197. // Send encoded username
  198. fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);
  199. $rply = $this->get_lines();
  200. $code = substr($rply,0,3);
  201. if($code != 334) {
  202. $this->error =
  203. array("error" => "Username not accepted from server",
  204. "smtp_code" => $code,
  205. "smtp_msg" => substr($rply,4));
  206. if($this->do_debug >= 1) {
  207. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  208. }
  209. return false;
  210. }
  211. // Send encoded password
  212. fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);
  213. $rply = $this->get_lines();
  214. $code = substr($rply,0,3);
  215. if($code != 235) {
  216. $this->error =
  217. array("error" => "Password not accepted from server",
  218. "smtp_code" => $code,
  219. "smtp_msg" => substr($rply,4));
  220. if($this->do_debug >= 1) {
  221. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  222. }
  223. return false;
  224. }
  225. return true;
  226. }
  227. /**
  228. * Returns true if connected to a server otherwise false
  229. * @access public
  230. * @return bool
  231. */
  232. public function Connected() {
  233. if(!empty($this->smtp_conn)) {
  234. $sock_status = socket_get_status($this->smtp_conn);
  235. if($sock_status["eof"]) {
  236. // the socket is valid but we are not connected
  237. if($this->do_debug >= 1) {
  238. echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected";
  239. }
  240. $this->Close();
  241. return false;
  242. }
  243. return true; // everything looks good
  244. }
  245. return false;
  246. }
  247. /**
  248. * Closes the socket and cleans up the state of the class.
  249. * It is not considered good to use this function without
  250. * first trying to use QUIT.
  251. * @access public
  252. * @return void
  253. */
  254. public function Close() {
  255. $this->error = null; // so there is no confusion
  256. $this->helo_rply = null;
  257. if(!empty($this->smtp_conn)) {
  258. // close the connection and cleanup
  259. fclose($this->smtp_conn);
  260. $this->smtp_conn = 0;
  261. }
  262. }
  263. /
  264. // SMTP COMMANDS
  265. /
  266. /**
  267. * Issues a data command and sends the msg_data to the server
  268. * finializing the mail transaction. $msg_data is the message
  269. * that is to be send with the headers. Each header needs to be
  270. * on a single line followed by a <CRLF> with the message headers
  271. * and the message body being seperated by and additional <CRLF>.
  272. *
  273. * Implements rfc 821: DATA <CRLF>
  274. *
  275. * SMTP CODE INTERMEDIATE: 354
  276. * [data]
  277. * <CRLF>.<CRLF>
  278. * SMTP CODE SUCCESS: 250
  279. * SMTP CODE FAILURE: 552,554,451,452
  280. * SMTP CODE FAILURE: 451,554
  281. * SMTP CODE ERROR : 500,501,503,421
  282. * @access public
  283. * @return bool
  284. */
  285. public function Data($msg_data) {
  286. $this->error = null; // so no confusion is caused
  287. if(!$this->connected()) {
  288. $this->error = array(
  289. "error" => "Called Data() without being connected");
  290. return false;
  291. }
  292. fputs($this->smtp_conn,"DATA" . $this->CRLF);
  293. $rply = $this->get_lines();
  294. $code = substr($rply,0,3);
  295. if($this->do_debug >= 2) {
  296. echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
  297. }
  298. if($code != 354) {
  299. $this->error =
  300. array("error" => "DATA command not accepted from server",
  301. "smtp_code" => $code,
  302. "smtp_msg" => substr($rply,4));
  303. if($this->do_debug >= 1) {
  304. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  305. }
  306. return false;
  307. }
  308. /* the server is ready to accept data!
  309. * according to rfc 821 we should not send more than 1000
  310. * including the CRLF
  311. * characters on a single line so we will break the data up
  312. * into lines by \r and/or \n then if needed we will break
  313. * each of those into smaller lines to fit within the limit.
  314. * in addition we will be looking for lines that start with
  315. * a period '.' and append and additional period '.' to that
  316. * line. NOTE: this does not count towards limit.
  317. */
  318. // normalize the line breaks so we know the explode works
  319. $msg_data = str_replace("\r\n","\n",$msg_data);
  320. $msg_data = str_replace("\r","\n",$msg_data);
  321. $lines = explode("\n",$msg_data);
  322. /* we need to find a good way to determine is headers are
  323. * in the msg_data or if it is a straight msg body
  324. * currently I am assuming rfc 822 definitions of msg headers
  325. * and if the first field of the first line (':' sperated)
  326. * does not contain a space then it _should_ be a header
  327. * and we can process all lines before a blank "" line as
  328. * headers.
  329. */
  330. $field = substr($lines[0],0,strpos($lines[0],":"));
  331. $in_headers = false;
  332. if(!empty($field) && !strstr($field," ")) {
  333. $in_headers = true;
  334. }
  335. $max_line_length = 998; // used below; set here for ease in change
  336. while(list(,$line) = @each($lines)) {
  337. $lines_out = null;
  338. if($line == "" && $in_headers) {
  339. $in_headers = false;
  340. }
  341. // ok we need to break this line up into several smaller lines
  342. while(strlen($line) > $max_line_length) {
  343. $pos = strrpos(substr($line,0,$max_line_length)," ");
  344. // Patch to fix DOS attack
  345. if(!$pos) {
  346. $pos = $max_line_length - 1;
  347. $lines_out[] = substr($line,0,$pos);
  348. $line = substr($line,$pos);
  349. } else {
  350. $lines_out[] = substr($line,0,$pos);
  351. $line = substr($line,$pos + 1);
  352. }
  353. /* if processing headers add a LWSP-char to the front of new line
  354. * rfc 822 on long msg headers
  355. */
  356. if($in_headers) {
  357. $line = "\t" . $line;
  358. }
  359. }
  360. $lines_out[] = $line;
  361. // send the lines to the server
  362. while(list(,$line_out) = @each($lines_out)) {
  363. if(strlen($line_out) > 0)
  364. {
  365. if(substr($line_out, 0, 1) == ".") {
  366. $line_out = "." . $line_out;
  367. }
  368. }
  369. fputs($this->smtp_conn,$line_out . $this->CRLF);
  370. }
  371. }
  372. // message data has been sent
  373. fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF);
  374. $rply = $this->get_lines();
  375. $code = substr($rply,0,3);
  376. if($this->do_debug >= 2) {
  377. echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
  378. }
  379. if($code != 250) {
  380. $this->error =
  381. array("error" => "DATA not accepted from server",
  382. "smtp_code" => $code,
  383. "smtp_msg" => substr($rply,4));
  384. if($this->do_debug >= 1) {
  385. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  386. }
  387. return false;
  388. }
  389. return true;
  390. }
  391. /**
  392. * Sends the HELO command to the smtp server.
  393. * This makes sure that we and the server are in
  394. * the same known state.
  395. *
  396. * Implements from rfc 821: HELO <SP> <domain> <CRLF>
  397. *
  398. * SMTP CODE SUCCESS: 250
  399. * SMTP CODE ERROR : 500, 501, 504, 421
  400. * @access public
  401. * @return bool
  402. */
  403. public function Hello($host = '') {
  404. $this->error = null; // so no confusion is caused
  405. if(!$this->connected()) {
  406. $this->error = array(
  407. "error" => "Called Hello() without being connected");
  408. return false;
  409. }
  410. // if hostname for HELO was not specified send default
  411. if(empty($host)) {
  412. // determine appropriate default to send to server
  413. $host = "localhost";
  414. }
  415. // Send extended hello first (RFC 2821)
  416. if(!$this->SendHello("EHLO", $host)) {
  417. if(!$this->SendHello("HELO", $host)) {
  418. return false;
  419. }
  420. }
  421. return true;
  422. }
  423. /**
  424. * Sends a HELO/EHLO command.
  425. * @access private
  426. * @return bool
  427. */
  428. private function SendHello($hello, $host) {
  429. fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF);
  430. $rply = $this->get_lines();
  431. $code = substr($rply,0,3);
  432. if($this->do_debug >= 2) {
  433. echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '<br />';
  434. }
  435. if($code != 250) {
  436. $this->error =
  437. array("error" => $hello . " not accepted from server",
  438. "smtp_code" => $code,
  439. "smtp_msg" => substr($rply,4));
  440. if($this->do_debug >= 1) {
  441. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  442. }
  443. return false;
  444. }
  445. $this->helo_rply = $rply;
  446. return true;
  447. }
  448. /**
  449. * Starts a mail transaction from the email address specified in
  450. * $from. Returns true if successful or false otherwise. If True
  451. * the mail transaction is started and then one or more Recipient
  452. * commands may be called followed by a Data command.
  453. *
  454. * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
  455. *
  456. * SMTP CODE SUCCESS: 250
  457. * SMTP CODE SUCCESS: 552,451,452
  458. * SMTP CODE SUCCESS: 500,501,421
  459. * @access public
  460. * @return bool
  461. */
  462. public function Mail($from) {
  463. $this->error = null; // so no confusion is caused
  464. if(!$this->connected()) {
  465. $this->error = array(
  466. "error" => "Called Mail() without being connected");
  467. return false;
  468. }
  469. $useVerp = ($this->do_verp ? "XVERP" : "");
  470. fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF);
  471. $rply = $this->get_lines();
  472. $code = substr($rply,0,3);
  473. if($this->do_debug >= 2) {
  474. echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
  475. }
  476. if($code != 250) {
  477. $this->error =
  478. array("error" => "MAIL not accepted from server",
  479. "smtp_code" => $code,
  480. "smtp_msg" => substr($rply,4));
  481. if($this->do_debug >= 1) {
  482. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  483. }
  484. return false;
  485. }
  486. return true;
  487. }
  488. /**
  489. * Sends the quit command to the server and then closes the socket
  490. * if there is no error or the $close_on_error argument is true.
  491. *
  492. * Implements from rfc 821: QUIT <CRLF>
  493. *
  494. * SMTP CODE SUCCESS: 221
  495. * SMTP CODE ERROR : 500
  496. * @access public
  497. * @return bool
  498. */
  499. public function Quit($close_on_error = true) {
  500. $this->error = null; // so there is no confusion
  501. if(!$this->connected()) {
  502. $this->error = array(
  503. "error" => "Called Quit() without being connected");
  504. return false;
  505. }
  506. // send the quit command to the server
  507. fputs($this->smtp_conn,"quit" . $this->CRLF);
  508. // get any good-bye messages
  509. $byemsg = $this->get_lines();
  510. if($this->do_debug >= 2) {
  511. echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />';
  512. }
  513. $rval = true;
  514. $e = null;
  515. $code = substr($byemsg,0,3);
  516. if($code != 221) {
  517. // use e as a tmp var cause Close will overwrite $this->error
  518. $e = array("error" => "SMTP server rejected quit command",
  519. "smtp_code" => $code,
  520. "smtp_rply" => substr($byemsg,4));
  521. $rval = false;
  522. if($this->do_debug >= 1) {
  523. echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />';
  524. }
  525. }
  526. if(empty($e) || $close_on_error) {
  527. $this->Close();
  528. }
  529. return $rval;
  530. }
  531. /**
  532. * Sends the command RCPT to the SMTP server with the TO: argument of $to.
  533. * Returns true if the recipient was accepted false if it was rejected.
  534. *
  535. * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
  536. *
  537. * SMTP CODE SUCCESS: 250,251
  538. * SMTP CODE FAILURE: 550,551,552,553,450,451,452
  539. * SMTP CODE ERROR : 500,501,503,421
  540. * @access public
  541. * @return bool
  542. */
  543. public function Recipient($to) {
  544. $this->error = null; // so no confusion is caused
  545. if(!$this->connected()) {
  546. $this->error = array(
  547. "error" => "Called Recipient() without being connected");
  548. return false;
  549. }
  550. fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF);
  551. $rply = $this->get_lines();
  552. $code = substr($rply,0,3);
  553. if($this->do_debug >= 2) {
  554. echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
  555. }
  556. if($code != 250 && $code != 251) {
  557. $this->error =
  558. array("error" => "RCPT not accepted from server",
  559. "smtp_code" => $code,
  560. "smtp_msg" => substr($rply,4));
  561. if($this->do_debug >= 1) {
  562. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  563. }
  564. return false;
  565. }
  566. return true;
  567. }
  568. /**
  569. * Sends the RSET command to abort and transaction that is
  570. * currently in progress. Returns true if successful false
  571. * otherwise.
  572. *
  573. * Implements rfc 821: RSET <CRLF>
  574. *
  575. * SMTP CODE SUCCESS: 250
  576. * SMTP CODE ERROR : 500,501,504,421
  577. * @access public
  578. * @return bool
  579. */
  580. public function Reset() {
  581. $this->error = null; // so no confusion is caused
  582. if(!$this->connected()) {
  583. $this->error = array(
  584. "error" => "Called Reset() without being connected");
  585. return false;
  586. }
  587. fputs($this->smtp_conn,"RSET" . $this->CRLF);
  588. $rply = $this->get_lines();
  589. $code = substr($rply,0,3);
  590. if($this->do_debug >= 2) {
  591. echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
  592. }
  593. if($code != 250) {
  594. $this->error =
  595. array("error" => "RSET failed",
  596. "smtp_code" => $code,
  597. "smtp_msg" => substr($rply,4));
  598. if($this->do_debug >= 1) {
  599. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  600. }
  601. return false;
  602. }
  603. return true;
  604. }
  605. /**
  606. * Starts a mail transaction from the email address specified in
  607. * $from. Returns true if successful or false otherwise. If True
  608. * the mail transaction is started and then one or more Recipient
  609. * commands may be called followed by a Data command. This command
  610. * will send the message to the users terminal if they are logged
  611. * in and send them an email.
  612. *
  613. * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
  614. *
  615. * SMTP CODE SUCCESS: 250
  616. * SMTP CODE SUCCESS: 552,451,452
  617. * SMTP CODE SUCCESS: 500,501,502,421
  618. * @access public
  619. * @return bool
  620. */
  621. public function SendAndMail($from) {
  622. $this->error = null; // so no confusion is caused
  623. if(!$this->connected()) {
  624. $this->error = array(
  625. "error" => "Called SendAndMail() without being connected");
  626. return false;
  627. }
  628. fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF);
  629. $rply = $this->get_lines();
  630. $code = substr($rply,0,3);
  631. if($this->do_debug >= 2) {
  632. echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
  633. }
  634. if($code != 250) {
  635. $this->error =
  636. array("error" => "SAML not accepted from server",
  637. "smtp_code" => $code,
  638. "smtp_msg" => substr($rply,4));
  639. if($this->do_debug >= 1) {
  640. echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
  641. }
  642. return false;
  643. }
  644. return true;
  645. }
  646. /**
  647. * This is an optional command for SMTP that this class does not
  648. * support. This method is here to make the RFC821 Definition
  649. * complete for this class and __may__ be implimented in the future
  650. *
  651. * Implements from rfc 821: TURN <CRLF>
  652. *
  653. * SMTP CODE SUCCESS: 250
  654. * SMTP CODE FAILURE: 502
  655. * SMTP CODE ERROR : 500, 503
  656. * @access public
  657. * @return bool
  658. */
  659. public function Turn() {
  660. $this->error = array("error" => "This method, TURN, of the SMTP ".
  661. "is not implemented");
  662. if($this->do_debug >= 1) {
  663. echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />';
  664. }
  665. return false;
  666. }
  667. /**
  668. * Get the current error
  669. * @access public
  670. * @return array
  671. */
  672. public function getError() {
  673. return $this->error;
  674. }
  675. /
  676. // INTERNAL FUNCTIONS
  677. /
  678. /**
  679. * Read in as many lines as possible
  680. * either before eof or socket timeout occurs on the operation.
  681. * With SMTP we can tell if we have more lines to read if the
  682. * 4th character is '-' symbol. If it is a space then we don't
  683. * need to read anything else.
  684. * @access private
  685. * @return string
  686. */
  687. private function get_lines() {
  688. $data = "";
  689. while($str = @fgets($this->smtp_conn,515)) {
  690. if($this->do_debug >= 4) {
  691. echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />';
  692. echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />';
  693. }
  694. $data .= $str;
  695. if($this->do_debug >= 4) {
  696. echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />';
  697. }
  698. // if 4th character is a space, we are done reading, break the loop
  699. if(substr($str,3,1) == " ") { break; }
  700. }
  701. return $data;
  702. }
  703. }
  704. ?>

三.class.pop3.php文件


  1. <?php
  2. /*~ class.pop3.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.1 |
  6. | Contact: via sourceforge.net support pages (also www.codeworxtech.com) |
  7. | Info: http://phpmailer.sourceforge.net |
  8. | Support: http://sourceforge.net/projects/phpmailer/ |
  9. | ------------------------------------------------------------------------- |
  10. | Admin: Andy Prevost (project admininistrator) |
  11. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  12. | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
  13. | Founder: Brent R. Matzelle (original founder) |
  14. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  15. | Copyright (c) 2001-2003, Brent R. Matzelle |
  16. | ------------------------------------------------------------------------- |
  17. | License: Distributed under the Lesser General Public License (LGPL) |
  18. | http://www.gnu.org/copyleft/lesser.html |
  19. | This program is distributed in the hope that it will be useful - WITHOUT |
  20. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  21. | FITNESS FOR A PARTICULAR PURPOSE. |
  22. | ------------------------------------------------------------------------- |
  23. | We offer a number of paid services (www.codeworxtech.com): |
  24. | - Web Hosting on highly optimized fast and secure servers |
  25. | - Technology Consulting |
  26. | - Oursourcing (highly qualified programmers and graphic designers) |
  27. '---------------------------------------------------------------------------'
  28. */
  29. /**
  30. * PHPMailer - PHP POP Before SMTP Authentication Class
  31. * NOTE: Designed for use with PHP version 5 and up
  32. * @package PHPMailer
  33. * @author Andy Prevost
  34. * @author Marcus Bointon
  35. * @copyright 2004 - 2009 Andy Prevost
  36. * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
  37. * @version $Id: class.pop3.php 444 2009-05-05 11:22:26Z coolbru $
  38. */
  39. /**
  40. * POP Before SMTP Authentication Class
  41. * Version 5.0.0
  42. *
  43. * Author: Richard Davey (rich@corephp.co.uk)
  44. * Modifications: Andy Prevost
  45. * License: LGPL, see PHPMailer License
  46. *
  47. * Specifically for PHPMailer to allow POP before SMTP authentication.
  48. * Does not yet work with APOP - if you have an APOP account, contact Richard Davey
  49. * and we can test changes to this script.
  50. *
  51. * This class is based on the structure of the SMTP class originally authored by Chris Ryan
  52. *
  53. * This class is rfc 1939 compliant and implements all the commands
  54. * required for POP3 connection, authentication and disconnection.
  55. *
  56. * @package PHPMailer
  57. * @author Richard Davey
  58. */
  59. class POP3 {
  60. /**
  61. * Default POP3 port
  62. * @var int
  63. */
  64. public $POP3_PORT = 110;
  65. /**
  66. * Default Timeout
  67. * @var int
  68. */
  69. public $POP3_TIMEOUT = 30;
  70. /**
  71. * POP3 Carriage Return + Line Feed
  72. * @var string
  73. */
  74. public $CRLF = "\r\n";
  75. /**
  76. * Displaying Debug warnings? (0 = now, 1+ = yes)
  77. * @var int
  78. */
  79. public $do_debug = 2;
  80. /**
  81. * POP3 Mail Server
  82. * @var string
  83. */
  84. public $host;
  85. /**
  86. * POP3 Port
  87. * @var int
  88. */
  89. public $port;
  90. /**
  91. * POP3 Timeout Value
  92. * @var int
  93. */
  94. public $tval;
  95. /**
  96. * POP3 Username
  97. * @var string
  98. */
  99. public $username;
  100. /**
  101. * POP3 Password
  102. * @var string
  103. */
  104. public $password;
  105. /
  106. // PROPERTIES, PRIVATE AND PROTECTED
  107. /
  108. private $pop_conn;
  109. private $connected;
  110. private $error; // Error log array
  111. /**
  112. * Constructor, sets the initial values
  113. * @access public
  114. * @return POP3
  115. */
  116. public function __construct() {
  117. $this->pop_conn = 0;
  118. $this->connected = false;
  119. $this->error = null;
  120. }
  121. /**
  122. * Combination of public events - connect, login, disconnect
  123. * @access public
  124. * @param string $host
  125. * @param integer $port
  126. * @param integer $tval
  127. * @param string $username
  128. * @param string $password
  129. */
  130. public function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) {
  131. $this->host = $host;
  132. // If no port value is passed, retrieve it
  133. if ($port == false) {
  134. $this->port = $this->POP3_PORT;
  135. } else {
  136. $this->port = $port;
  137. }
  138. // If no port value is passed, retrieve it
  139. if ($tval == false) {
  140. $this->tval = $this->POP3_TIMEOUT;
  141. } else {
  142. $this->tval = $tval;
  143. }
  144. $this->do_debug = $debug_level;
  145. $this->username = $username;
  146. $this->password = $password;
  147. // Refresh the error log
  148. $this->error = null;
  149. // Connect
  150. $result = $this->Connect($this->host, $this->port, $this->tval);
  151. if ($result) {
  152. $login_result = $this->Login($this->username, $this->password);
  153. if ($login_result) {
  154. $this->Disconnect();
  155. return true;
  156. }
  157. }
  158. // We need to disconnect regardless if the login succeeded
  159. $this->Disconnect();
  160. return false;
  161. }
  162. /**
  163. * Connect to the POP3 server
  164. * @access public
  165. * @param string $host
  166. * @param integer $port
  167. * @param integer $tval
  168. * @return boolean
  169. */
  170. public function Connect ($host, $port = false, $tval = 30) {
  171. // Are we already connected?
  172. if ($this->connected) {
  173. return true;
  174. }
  175. /*
  176. On Windows this will raise a PHP Warning error if the hostname doesn't exist.
  177. Rather than supress it with @fsockopen, let's capture it cleanly instead
  178. */
  179. set_error_handler(array(&$this, 'catchWarning'));
  180. // Connect to the POP3 server
  181. $this->pop_conn = fsockopen($host, // POP3 Host
  182. $port, // Port #
  183. $errno, // Error Number
  184. $errstr, // Error Message
  185. $tval); // Timeout (seconds)
  186. // Restore the error handler
  187. restore_error_handler();
  188. // Does the Error Log now contain anything?
  189. if ($this->error && $this->do_debug >= 1) {
  190. $this->displayErrors();
  191. }
  192. // Did we connect?
  193. if ($this->pop_conn == false) {
  194. // It would appear not...
  195. $this->error = array(
  196. 'error' => "Failed to connect to server $host on port $port",
  197. 'errno' => $errno,
  198. 'errstr' => $errstr
  199. );
  200. if ($this->do_debug >= 1) {
  201. $this->displayErrors();
  202. }
  203. return false;
  204. }
  205. // Increase the stream time-out
  206. // Check for PHP 4.3.0 or later
  207. if (version_compare(phpversion(), '5.0.0', 'ge')) {
  208. stream_set_timeout($this->pop_conn, $tval, 0);
  209. } else {
  210. // Does not work on Windows
  211. if (substr(PHP_OS, 0, 3) !== 'WIN') {
  212. socket_set_timeout($this->pop_conn, $tval, 0);
  213. }
  214. }
  215. // Get the POP3 server response
  216. $pop3_response = $this->getResponse();
  217. // Check for the +OK
  218. if ($this->checkResponse($pop3_response)) {
  219. // The connection is established and the POP3 server is talking
  220. $this->connected = true;
  221. return true;
  222. }
  223. }
  224. /**
  225. * Login to the POP3 server (does not support APOP yet)
  226. * @access public
  227. * @param string $username
  228. * @param string $password
  229. * @return boolean
  230. */
  231. public function Login ($username = '', $password = '') {
  232. if ($this->connected == false) {
  233. $this->error = 'Not connected to POP3 server';
  234. if ($this->do_debug >= 1) {
  235. $this->displayErrors();
  236. }
  237. }
  238. if (empty($username)) {
  239. $username = $this->username;
  240. }
  241. if (empty($password)) {
  242. $password = $this->password;
  243. }
  244. $pop_username = "USER $username" . $this->CRLF;
  245. $pop_password = "PASS $password" . $this->CRLF;
  246. // Send the Username
  247. $this->sendString($pop_username);
  248. $pop3_response = $this->getResponse();
  249. if ($this->checkResponse($pop3_response)) {
  250. // Send the Password
  251. $this->sendString($pop_password);
  252. $pop3_response = $this->getResponse();
  253. if ($this->checkResponse($pop3_response)) {
  254. return true;
  255. } else {
  256. return false;
  257. }
  258. } else {
  259. return false;
  260. }
  261. }
  262. /**
  263. * Disconnect from the POP3 server
  264. * @access public
  265. */
  266. public function Disconnect () {
  267. $this->sendString('QUIT');
  268. fclose($this->pop_conn);
  269. }
  270. /
  271. // Private Methods
  272. /
  273. /**
  274. * Get the socket response back.
  275. * $size is the maximum number of bytes to retrieve
  276. * @access private
  277. * @param integer $size
  278. * @return string
  279. */
  280. private function getResponse ($size = 128) {
  281. $pop3_response = fgets($this->pop_conn, $size);
  282. return $pop3_response;
  283. }
  284. /**
  285. * Send a string down the open socket connection to the POP3 server
  286. * @access private
  287. * @param string $string
  288. * @return integer
  289. */
  290. private function sendString ($string) {
  291. $bytes_sent = fwrite($this->pop_conn, $string, strlen($string));
  292. return $bytes_sent;
  293. }
  294. /**
  295. * Checks the POP3 server response for +OK or -ERR
  296. * @access private
  297. * @param string $string
  298. * @return boolean
  299. */
  300. private function checkResponse ($string) {
  301. if (substr($string, 0, 3) !== '+OK') {
  302. $this->error = array(
  303. 'error' => "Server reported an error: $string",
  304. 'errno' => 0,
  305. 'errstr' => ''
  306. );
  307. if ($this->do_debug >= 1) {
  308. $this->displayErrors();
  309. }
  310. return false;
  311. } else {
  312. return true;
  313. }
  314. }
  315. /**
  316. * If debug is enabled, display the error message array
  317. * @access private
  318. */
  319. private function displayErrors () {
  320. echo '<pre>';
  321. foreach ($this->error as $single_error) {
  322. print_r($single_error);
  323. }
  324. echo '</pre>';
  325. }
  326. /**
  327. * Takes over from PHP for the socket warning handler
  328. * @access private
  329. * @param integer $errno
  330. * @param string $errstr
  331. * @param string $errfile
  332. * @param integer $errline
  333. */
  334. private function catchWarning ($errno, $errstr, $errfile, $errline) {
  335. $this->error[] = array(
  336. 'error' => "Connecting to the POP3 server raised a PHP warning: ",
  337. 'errno' => $errno,
  338. 'errstr' => $errstr
  339. );
  340. }
  341. // End of class
  342. }
  343. ?>





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/856319
推荐阅读
相关标签
  

闽ICP备14008679号