1<?php
2/*~ class.phpmailer.php
3.---------------------------------------------------------------------------.
4|  Software: PHPMailer - PHP email class                                    |
5|   Version: 5.2.2                                                          |
6|      Site: https://code.google.com/a/apache-extras.org/p/phpmailer/       |
7| ------------------------------------------------------------------------- |
8|     Admin: Jim Jagielski (project admininistrator)                        |
9|   Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
10|          : Marcus Bointon (coolbru) coolbru@users.sourceforge.net         |
11|          : Jim Jagielski (jimjag) jimjag@gmail.com                        |
12|   Founder: Brent R. Matzelle (original founder)                           |
13| Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved.              |
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*/
24
25/**
26 * PHPMailer - PHP email creation and transport class
27 * NOTE: Requires PHP version 5 or later
28 * @package PHPMailer
29 * @author Andy Prevost
30 * @author Marcus Bointon
31 * @author Jim Jagielski
32 * @copyright 2010 - 2012 Jim Jagielski
33 * @copyright 2004 - 2009 Andy Prevost
34 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
35 */
36
37if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
38
39/**
40 * PHP email creation and transport class
41 * @package PHPMailer
42 */
43class PHPMailer {
44
45  /////////////////////////////////////////////////
46  // PROPERTIES, PUBLIC
47  /////////////////////////////////////////////////
48
49  /**
50   * Email priority (1 = High, 3 = Normal, 5 = low).
51   * @var int
52   */
53  public $Priority          = 3;
54
55  /**
56   * Sets the CharSet of the message.
57   * @var string
58   */
59  public $CharSet           = 'iso-8859-1';
60
61  /**
62   * Sets the Content-type of the message.
63   * @var string
64   */
65  public $ContentType       = 'text/plain';
66
67  /**
68   * Sets the Encoding of the message. Options for this are
69   *  "8bit", "7bit", "binary", "base64", and "quoted-printable".
70   * @var string
71   */
72  public $Encoding          = '8bit';
73
74  /**
75   * Holds the most recent mailer error message.
76   * @var string
77   */
78  public $ErrorInfo         = '';
79
80  /**
81   * Sets the From email address for the message.
82   * @var string
83   */
84  public $From              = 'root@localhost';
85
86  /**
87   * Sets the From name of the message.
88   * @var string
89   */
90  public $FromName          = 'Root User';
91
92  /**
93   * Sets the Sender email (Return-Path) of the message.  If not empty,
94   * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
95   * @var string
96   */
97  public $Sender            = '';
98
99  /**
100   * Sets the Return-Path of the message.  If empty, it will
101   * be set to either From or Sender.
102   * @var string
103   */
104  public $ReturnPath        = '';
105
106  /**
107   * Sets the Subject of the message.
108   * @var string
109   */
110  public $Subject           = '';
111
112  /**
113   * Sets the Body of the message.  This can be either an HTML or text body.
114   * If HTML then run IsHTML(true).
115   * @var string
116   */
117  public $Body              = '';
118
119  /**
120   * Sets the text-only body of the message.  This automatically sets the
121   * email to multipart/alternative.  This body can be read by mail
122   * clients that do not have HTML email capability such as mutt. Clients
123   * that can read HTML will view the normal Body.
124   * @var string
125   */
126  public $AltBody           = '';
127
128  /**
129   * Stores the complete compiled MIME message body.
130   * @var string
131   * @access protected
132   */
133  protected $MIMEBody       = '';
134
135  /**
136   * Stores the complete compiled MIME message headers.
137   * @var string
138   * @access protected
139   */
140  protected $MIMEHeader     = '';
141
142  /**
143   * Stores the extra header list which CreateHeader() doesn't fold in
144   * @var string
145   * @access protected
146  */
147  protected $mailHeader     = '';
148
149  /**
150   * Sets word wrapping on the body of the message to a given number of
151   * characters.
152   * @var int
153   */
154  public $WordWrap          = 0;
155
156  /**
157   * Method to send mail: ("mail", "sendmail", or "smtp").
158   * @var string
159   */
160  public $Mailer            = 'mail';
161
162  /**
163   * Sets the path of the sendmail program.
164   * @var string
165   */
166  public $Sendmail          = '/usr/sbin/sendmail';
167
168  /**
169   * Determine if mail() uses a fully sendmail compatible MTA that
170   * supports sendmail's "-oi -f" options
171   * @var boolean
172   */
173  public $UseSendmailOptions	= true;
174
175  /**
176   * Path to PHPMailer plugins.  Useful if the SMTP class
177   * is in a different directory than the PHP include path.
178   * @var string
179   */
180  public $PluginDir         = '';
181
182  /**
183   * Sets the email address that a reading confirmation will be sent.
184   * @var string
185   */
186  public $ConfirmReadingTo  = '';
187
188  /**
189   * Sets the hostname to use in Message-Id and Received headers
190   * and as default HELO string. If empty, the value returned
191   * by SERVER_NAME is used or 'localhost.localdomain'.
192   * @var string
193   */
194  public $Hostname          = '';
195
196  /**
197   * Sets the message ID to be used in the Message-Id header.
198   * If empty, a unique id will be generated.
199   * @var string
200   */
201  public $MessageID         = '';
202
203  /**
204   * Sets the message Date to be used in the Date header.
205   * If empty, the current date will be added.
206   * @var string
207   */
208  public $MessageDate       = '';
209
210  /////////////////////////////////////////////////
211  // PROPERTIES FOR SMTP
212  /////////////////////////////////////////////////
213
214  /**
215   * Sets the SMTP hosts.
216   *
217   * All hosts must be separated by a
218   * semicolon.  You can also specify a different port
219   * for each host by using this format: [hostname:port]
220   * (e.g. "smtp1.example.com:25;smtp2.example.com").
221   * Hosts will be tried in order.
222   * @var string
223   */
224  public $Host          = 'localhost';
225
226  /**
227   * Sets the default SMTP server port.
228   * @var int
229   */
230  public $Port          = 25;
231
232  /**
233   * Sets the SMTP HELO of the message (Default is $Hostname).
234   * @var string
235   */
236  public $Helo          = '';
237
238  /**
239   * Sets connection prefix. Options are "", "ssl" or "tls"
240   * @var string
241   */
242  public $SMTPSecure    = '';
243
244  /**
245   * Sets SMTP authentication. Utilizes the Username and Password variables.
246   * @var bool
247   */
248  public $SMTPAuth      = false;
249
250  /**
251   * Sets SMTP username.
252   * @var string
253   */
254  public $Username      = '';
255
256  /**
257   * Sets SMTP password.
258   * @var string
259   */
260  public $Password      = '';
261
262  /**
263   *  Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM  (default LOGIN)
264   *  @var string
265   */
266  public $AuthType      = '';
267
268  /**
269   *  Sets SMTP realm.
270   *  @var string
271   */
272  public $Realm         = '';
273
274  /**
275   *  Sets SMTP workstation.
276   *  @var string
277   */
278  public $Workstation   = '';
279
280  /**
281   * Sets the SMTP server timeout in seconds.
282   * This function will not work with the win32 version.
283   * @var int
284   */
285  public $Timeout       = 10;
286
287  /**
288   * Sets SMTP class debugging on or off.
289   * @var bool
290   */
291  public $SMTPDebug     = false;
292
293  /**
294   * Sets the function/method to use for debugging output.
295   * Right now we only honor "echo" or "error_log"
296   * @var string
297   */
298  public $Debugoutput     = "echo";
299
300  /**
301   * Prevents the SMTP connection from being closed after each mail
302   * sending.  If this is set to true then to close the connection
303   * requires an explicit call to SmtpClose().
304   * @var bool
305   */
306  public $SMTPKeepAlive = false;
307
308  /**
309   * Provides the ability to have the TO field process individual
310   * emails, instead of sending to entire TO addresses
311   * @var bool
312   */
313  public $SingleTo      = false;
314
315   /**
316   * If SingleTo is true, this provides the array to hold the email addresses
317   * @var bool
318   */
319  public $SingleToArray = array();
320
321 /**
322   * Provides the ability to change the generic line ending
323   * NOTE: The default remains '\n'. We force CRLF where we KNOW
324   *        it must be used via self::CRLF
325   * @var string
326   */
327  public $LE              = "\n";
328
329   /**
330   * Used with DKIM Signing
331   * required parameter if DKIM is enabled
332   *
333   * domain selector example domainkey
334   * @var string
335   */
336  public $DKIM_selector   = '';
337
338  /**
339   * Used with DKIM Signing
340   * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email
341   * @var string
342   */
343  public $DKIM_identity   = '';
344
345  /**
346   * Used with DKIM Signing
347   * optional parameter if your private key requires a passphras
348   * @var string
349   */
350  public $DKIM_passphrase   = '';
351
352  /**
353   * Used with DKIM Singing
354   * required if DKIM is enabled, in format of email address 'domain.com'
355   * @var string
356   */
357  public $DKIM_domain     = '';
358
359  /**
360   * Used with DKIM Signing
361   * required if DKIM is enabled, path to private key file
362   * @var string
363   */
364  public $DKIM_private    = '';
365
366  /**
367   * Callback Action function name.
368   * The function that handles the result of the send email action.
369   * It is called out by Send() for each email sent.
370   *
371   * Value can be:
372   * - 'function_name' for function names
373   * - 'Class::Method' for static method calls
374   * - array($object, 'Method') for calling methods on $object
375   * See http://php.net/is_callable manual page for more details.
376   *
377   * Parameters:
378   *   bool    $result        result of the send action
379   *   string  $to            email address of the recipient
380   *   string  $cc            cc email addresses
381   *   string  $bcc           bcc email addresses
382   *   string  $subject       the subject
383   *   string  $body          the email body
384   *   string  $from          email address of sender
385   * @var string
386   */
387  public $action_function = ''; //'callbackAction';
388
389  /**
390   * Sets the PHPMailer Version number
391   * @var string
392   */
393  public $Version         = '5.2.2';
394
395  /**
396   * What to use in the X-Mailer header
397   * @var string NULL for default, whitespace for None, or actual string to use
398   */
399  public $XMailer         = '';
400
401  /////////////////////////////////////////////////
402  // PROPERTIES, PRIVATE AND PROTECTED
403  /////////////////////////////////////////////////
404
405  /**
406   * @var SMTP An instance of the SMTP sender class
407   * @access protected
408   */
409  protected   $smtp           = null;
410  /**
411   * @var array An array of 'to' addresses
412   * @access protected
413   */
414  protected   $to             = array();
415  /**
416   * @var array An array of 'cc' addresses
417   * @access protected
418   */
419  protected   $cc             = array();
420  /**
421   * @var array An array of 'bcc' addresses
422   * @access protected
423   */
424  protected   $bcc            = array();
425  /**
426   * @var array An array of reply-to name and address
427   * @access protected
428   */
429  protected   $ReplyTo        = array();
430  /**
431   * @var array An array of all kinds of addresses: to, cc, bcc, replyto
432   * @access protected
433   */
434  protected   $all_recipients = array();
435  /**
436   * @var array An array of attachments
437   * @access protected
438   */
439  protected   $attachment     = array();
440  /**
441   * @var array An array of custom headers
442   * @access protected
443   */
444  protected   $CustomHeader   = array();
445  /**
446   * @var string The message's MIME type
447   * @access protected
448   */
449  protected   $message_type   = '';
450  /**
451   * @var array An array of MIME boundary strings
452   * @access protected
453   */
454  protected   $boundary       = array();
455  /**
456   * @var array An array of available languages
457   * @access protected
458   */
459  protected   $language       = array();
460  /**
461   * @var integer The number of errors encountered
462   * @access protected
463   */
464  protected   $error_count    = 0;
465  /**
466   * @var string The filename of a DKIM certificate file
467   * @access protected
468   */
469  protected   $sign_cert_file = '';
470  /**
471   * @var string The filename of a DKIM key file
472   * @access protected
473   */
474  protected   $sign_key_file  = '';
475  /**
476   * @var string The password of a DKIM key
477   * @access protected
478   */
479  protected   $sign_key_pass  = '';
480  /**
481   * @var boolean Whether to throw exceptions for errors
482   * @access protected
483   */
484  protected   $exceptions     = false;
485
486  /////////////////////////////////////////////////
487  // CONSTANTS
488  /////////////////////////////////////////////////
489
490  const STOP_MESSAGE  = 0; // message only, continue processing
491  const STOP_CONTINUE = 1; // message?, likely ok to continue processing
492  const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
493  const CRLF = "\r\n";     // SMTP RFC specified EOL
494
495  /////////////////////////////////////////////////
496  // METHODS, VARIABLES
497  /////////////////////////////////////////////////
498
499  /**
500   * Calls actual mail() function, but in a safe_mode aware fashion
501   * Also, unless sendmail_path points to sendmail (or something that
502   * claims to be sendmail), don't pass params (not a perfect fix,
503   * but it will do)
504   * @param string $to To
505   * @param string $subject Subject
506   * @param string $body Message Body
507   * @param string $header Additional Header(s)
508   * @param string $params Params
509   * @access private
510   * @return bool
511   */
512  private function mail_passthru($to, $subject, $body, $header, $params) {
513    if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
514        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
515    } else {
516        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
517    }
518    return $rt;
519  }
520
521  /**
522   * Outputs debugging info via user-defined method
523   * @param string $str
524   */
525  private function edebug($str) {
526    if ($this->Debugoutput == "error_log") {
527        error_log($str);
528    } else {
529        echo $str;
530    }
531  }
532
533  /**
534   * Constructor
535   * @param boolean $exceptions Should we throw external exceptions?
536   */
537  public function __construct($exceptions = false) {
538    $this->exceptions = ($exceptions == true);
539  }
540
541  /**
542   * Sets message type to HTML.
543   * @param bool $ishtml
544   * @return void
545   */
546  public function IsHTML($ishtml = true) {
547    if ($ishtml) {
548      $this->ContentType = 'text/html';
549    } else {
550      $this->ContentType = 'text/plain';
551    }
552  }
553
554  /**
555   * Sets Mailer to send message using SMTP.
556   * @return void
557   * @deprecated
558   */
559  public function IsSMTP() {
560    $this->Mailer = 'smtp';
561  }
562
563  /**
564   * Sets Mailer to send message using PHP mail() function.
565   * @return void
566   * @deprecated
567   */
568  public function IsMail() {
569    $this->Mailer = 'mail';
570  }
571
572  /**
573   * Sets Mailer to send message using the $Sendmail program.
574   * @return void
575   * @deprecated
576   */
577  public function IsSendmail() {
578    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
579      $this->Sendmail = '/var/qmail/bin/sendmail';
580    }
581    $this->Mailer = 'sendmail';
582  }
583
584  /**
585   * Sets Mailer to send message using the qmail MTA.
586   * @return void
587   * @deprecated
588   */
589  public function IsQmail() {
590    if (stristr(ini_get('sendmail_path'), 'qmail')) {
591      $this->Sendmail = '/var/qmail/bin/sendmail';
592    }
593    $this->Mailer = 'sendmail';
594  }
595
596  /////////////////////////////////////////////////
597  // METHODS, RECIPIENTS
598  /////////////////////////////////////////////////
599
600  /**
601   * Adds a "To" address.
602   * @param string $address
603   * @param string $name
604   * @return boolean true on success, false if address already used
605   */
606  public function AddAddress($address, $name = '') {
607    return $this->AddAnAddress('to', $address, $name);
608  }
609
610  /**
611   * Adds a "Cc" address.
612   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
613   * @param string $address
614   * @param string $name
615   * @return boolean true on success, false if address already used
616   */
617  public function AddCC($address, $name = '') {
618    return $this->AddAnAddress('cc', $address, $name);
619  }
620
621  /**
622   * Adds a "Bcc" address.
623   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
624   * @param string $address
625   * @param string $name
626   * @return boolean true on success, false if address already used
627   */
628  public function AddBCC($address, $name = '') {
629    return $this->AddAnAddress('bcc', $address, $name);
630  }
631
632  /**
633   * Adds a "Reply-to" address.
634   * @param string $address
635   * @param string $name
636   * @return boolean
637   */
638  public function AddReplyTo($address, $name = '') {
639    return $this->AddAnAddress('Reply-To', $address, $name);
640  }
641
642  /**
643   * Adds an address to one of the recipient arrays
644   * Addresses that have been added already return false, but do not throw exceptions
645   * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
646   * @param string $address The email address to send to
647   * @param string $name
648   * @throws phpmailerException
649   * @return boolean true on success, false if address already used or invalid in some way
650   * @access protected
651   */
652  protected function AddAnAddress($kind, $address, $name = '') {
653    if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
654      $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
655      if ($this->exceptions) {
656        throw new phpmailerException('Invalid recipient array: ' . $kind);
657      }
658      if ($this->SMTPDebug) {
659        $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
660      }
661      return false;
662    }
663    $address = trim($address);
664    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
665    if (!$this->ValidateAddress($address)) {
666      $this->SetError($this->Lang('invalid_address').': '. $address);
667      if ($this->exceptions) {
668        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
669      }
670      if ($this->SMTPDebug) {
671        $this->edebug($this->Lang('invalid_address').': '.$address);
672      }
673      return false;
674    }
675    if ($kind != 'Reply-To') {
676      if (!isset($this->all_recipients[strtolower($address)])) {
677        array_push($this->$kind, array($address, $name));
678        $this->all_recipients[strtolower($address)] = true;
679        return true;
680      }
681    } else {
682      if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
683        $this->ReplyTo[strtolower($address)] = array($address, $name);
684      return true;
685    }
686  }
687  return false;
688}
689
690/**
691 * Set the From and FromName properties
692 * @param string $address
693 * @param string $name
694 * @param int $auto Also set Reply-To and Sender
695   * @throws phpmailerException
696 * @return boolean
697 */
698  public function SetFrom($address, $name = '', $auto = 1) {
699    $address = trim($address);
700    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
701    if (!$this->ValidateAddress($address)) {
702      $this->SetError($this->Lang('invalid_address').': '. $address);
703      if ($this->exceptions) {
704        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
705      }
706      if ($this->SMTPDebug) {
707        $this->edebug($this->Lang('invalid_address').': '.$address);
708      }
709      return false;
710    }
711    $this->From = $address;
712    $this->FromName = $name;
713    if ($auto) {
714      if (empty($this->ReplyTo)) {
715        $this->AddAnAddress('Reply-To', $address, $name);
716      }
717      if (empty($this->Sender)) {
718        $this->Sender = $address;
719      }
720    }
721    return true;
722  }
723
724  /**
725   * Check that a string looks roughly like an email address should
726   * Static so it can be used without instantiation, public so people can overload
727   * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
728   * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
729   * not allow a@b type valid addresses :(
730   * @link http://squiloople.com/2009/12/20/email-address-validation/
731   * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
732   * @param string $address The email address to check
733   * @return boolean
734   * @static
735   * @access public
736   */
737  public static function ValidateAddress($address) {
738	return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[	 ])+|(?>[	 ]*\x0D\x0A)?[	 ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){7,})((?6)(?>:(?6)){0,5})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){5,})(?8)?::(?>((?6)(?>:(?6)){0,3}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
739  }
740
741  /////////////////////////////////////////////////
742  // METHODS, MAIL SENDING
743  /////////////////////////////////////////////////
744
745  /**
746   * Creates message and assigns Mailer. If the message is
747   * not sent successfully then it returns false.  Use the ErrorInfo
748   * variable to view description of the error.
749   * @throws phpmailerException
750   * @return bool
751   */
752  public function Send() {
753    try {
754      if(!$this->PreSend()) return false;
755      return $this->PostSend();
756    } catch (phpmailerException $e) {
757      $this->mailHeader = '';
758      $this->SetError($e->getMessage());
759      if ($this->exceptions) {
760        throw $e;
761      }
762      return false;
763    }
764  }
765
766  /**
767   * Prep mail by constructing all message entities
768   * @throws phpmailerException
769   * @return bool
770   */
771  public function PreSend() {
772    try {
773      $this->mailHeader = "";
774      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
775        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
776      }
777
778      // Set whether the message is multipart/alternative
779      if(!empty($this->AltBody)) {
780        $this->ContentType = 'multipart/alternative';
781      }
782
783      $this->error_count = 0; // reset errors
784      $this->SetMessageType();
785      //Refuse to send an empty message
786      if (empty($this->Body)) {
787        throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
788      }
789
790      $this->MIMEHeader = $this->CreateHeader();
791      $this->MIMEBody = $this->CreateBody();
792
793      // To capture the complete message when using mail(), create
794      // an extra header list which CreateHeader() doesn't fold in
795      if ($this->Mailer == 'mail') {
796        if (count($this->to) > 0) {
797          $this->mailHeader .= $this->AddrAppend("To", $this->to);
798        } else {
799          $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
800        }
801        $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
802        // if(count($this->cc) > 0) {
803            // $this->mailHeader .= $this->AddrAppend("Cc", $this->cc);
804        // }
805      }
806
807      // digitally sign with DKIM if enabled
808      if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
809        $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
810        $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
811      }
812
813      return true;
814
815    } catch (phpmailerException $e) {
816      $this->SetError($e->getMessage());
817      if ($this->exceptions) {
818        throw $e;
819      }
820      return false;
821    }
822  }
823
824  /**
825   * Actual Email transport function
826   * Send the email via the selected mechanism
827   * @throws phpmailerException
828   * @return bool
829   */
830  public function PostSend() {
831    try {
832      // Choose the mailer and send through it
833      switch($this->Mailer) {
834        case 'sendmail':
835          return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
836        case 'smtp':
837          return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
838        case 'mail':
839          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
840        default:
841          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
842      }
843    } catch (phpmailerException $e) {
844      $this->SetError($e->getMessage());
845      if ($this->exceptions) {
846        throw $e;
847      }
848      if ($this->SMTPDebug) {
849        $this->edebug($e->getMessage()."\n");
850      }
851    }
852    return false;
853  }
854
855  /**
856   * Sends mail using the $Sendmail program.
857   * @param string $header The message headers
858   * @param string $body The message body
859   * @throws phpmailerException
860   * @access protected
861   * @return bool
862   */
863  protected function SendmailSend($header, $body) {
864    if ($this->Sender != '') {
865      $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
866    } else {
867      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
868    }
869    if ($this->SingleTo === true) {
870      foreach ($this->SingleToArray as $val) {
871        if(!@$mail = popen($sendmail, 'w')) {
872          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
873        }
874        fputs($mail, "To: " . $val . "\n");
875        fputs($mail, $header);
876        fputs($mail, $body);
877        $result = pclose($mail);
878        // implement call back function if it exists
879        $isSent = ($result == 0) ? 1 : 0;
880        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
881        if($result != 0) {
882          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
883        }
884      }
885    } else {
886      if(!@$mail = popen($sendmail, 'w')) {
887        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
888      }
889      fputs($mail, $header);
890      fputs($mail, $body);
891      $result = pclose($mail);
892      // implement call back function if it exists
893      $isSent = ($result == 0) ? 1 : 0;
894      $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
895      if($result != 0) {
896        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
897      }
898    }
899    return true;
900  }
901
902  /**
903   * Sends mail using the PHP mail() function.
904   * @param string $header The message headers
905   * @param string $body The message body
906     * @throws phpmailerException
907   * @access protected
908   * @return bool
909   */
910  protected function MailSend($header, $body) {
911    $toArr = array();
912    foreach($this->to as $t) {
913      $toArr[] = $this->AddrFormat($t);
914    }
915    $to = implode(', ', $toArr);
916
917    if (empty($this->Sender)) {
918      $params = "-oi ";
919    } else {
920      $params = sprintf("-oi -f%s", $this->Sender);
921    }
922    if ($this->Sender != '' and !ini_get('safe_mode')) {
923      $old_from = ini_get('sendmail_from');
924      ini_set('sendmail_from', $this->Sender);
925    }
926      $rt = false;
927    if ($this->SingleTo === true && count($toArr) > 1) {
928      foreach ($toArr as $val) {
929        $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
930        // implement call back function if it exists
931        $isSent = ($rt == 1) ? 1 : 0;
932        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
933      }
934    } else {
935      $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
936      // implement call back function if it exists
937      $isSent = ($rt == 1) ? 1 : 0;
938      $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
939    }
940    if (isset($old_from)) {
941      ini_set('sendmail_from', $old_from);
942    }
943    if(!$rt) {
944      throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
945    }
946    return true;
947  }
948
949  /**
950   * Sends mail via SMTP using PhpSMTP
951   * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
952   * @param string $header The message headers
953   * @param string $body The message body
954   * @throws phpmailerException
955   * @uses SMTP
956   * @access protected
957   * @return bool
958   */
959  protected function SmtpSend($header, $body) {
960    require_once $this->PluginDir . 'class.smtp.php';
961    $bad_rcpt = array();
962
963    if(!$this->SmtpConnect()) {
964      throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
965    }
966    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
967    if(!$this->smtp->Mail($smtp_from)) {
968      throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
969    }
970
971    // Attempt to send attach all recipients
972    foreach($this->to as $to) {
973      if (!$this->smtp->Recipient($to[0])) {
974        $bad_rcpt[] = $to[0];
975        // implement call back function if it exists
976        $isSent = 0;
977        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
978      } else {
979        // implement call back function if it exists
980        $isSent = 1;
981        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
982      }
983    }
984    foreach($this->cc as $cc) {
985      if (!$this->smtp->Recipient($cc[0])) {
986        $bad_rcpt[] = $cc[0];
987        // implement call back function if it exists
988        $isSent = 0;
989        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
990      } else {
991        // implement call back function if it exists
992        $isSent = 1;
993        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
994      }
995    }
996    foreach($this->bcc as $bcc) {
997      if (!$this->smtp->Recipient($bcc[0])) {
998        $bad_rcpt[] = $bcc[0];
999        // implement call back function if it exists
1000        $isSent = 0;
1001        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
1002      } else {
1003        // implement call back function if it exists
1004        $isSent = 1;
1005        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
1006      }
1007    }
1008
1009
1010    if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
1011      $badaddresses = implode(', ', $bad_rcpt);
1012      throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
1013    }
1014    if(!$this->smtp->Data($header . $body)) {
1015      throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
1016    }
1017    if($this->SMTPKeepAlive == true) {
1018      $this->smtp->Reset();
1019    } else {
1020        $this->smtp->Quit();
1021        $this->smtp->Close();
1022    }
1023    return true;
1024  }
1025
1026  /**
1027   * Initiates a connection to an SMTP server.
1028   * Returns false if the operation failed.
1029   * @uses SMTP
1030   * @access public
1031   * @throws phpmailerException
1032   * @return bool
1033   */
1034  public function SmtpConnect() {
1035    if(is_null($this->smtp)) {
1036      $this->smtp = new SMTP;
1037    }
1038
1039    $this->smtp->Timeout = $this->Timeout;
1040    $this->smtp->do_debug = $this->SMTPDebug;
1041    $hosts = explode(';', $this->Host);
1042    $index = 0;
1043    $connection = $this->smtp->Connected();
1044
1045    // Retry while there is no connection
1046    try {
1047      while($index < count($hosts) && !$connection) {
1048        $hostinfo = array();
1049        if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
1050          $host = $hostinfo[1];
1051          $port = $hostinfo[2];
1052        } else {
1053          $host = $hosts[$index];
1054          $port = $this->Port;
1055        }
1056
1057        $tls = ($this->SMTPSecure == 'tls');
1058        $ssl = ($this->SMTPSecure == 'ssl');
1059
1060        if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
1061
1062          $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
1063          $this->smtp->Hello($hello);
1064
1065          if ($tls) {
1066            if (!$this->smtp->StartTLS()) {
1067              throw new phpmailerException($this->Lang('tls'));
1068            }
1069
1070            //We must resend HELO after tls negotiation
1071            $this->smtp->Hello($hello);
1072          }
1073
1074          $connection = true;
1075          if ($this->SMTPAuth) {
1076            if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType,
1077                                           $this->Realm, $this->Workstation)) {
1078              throw new phpmailerException($this->Lang('authenticate'));
1079            }
1080          }
1081        }
1082        $index++;
1083      if (!$connection) {
1084        throw new phpmailerException($this->Lang('connect_host'));
1085      }
1086      }
1087    } catch (phpmailerException $e) {
1088      $this->smtp->Reset();
1089      if ($this->exceptions) {
1090        throw $e;
1091      }
1092    }
1093    return true;
1094  }
1095
1096  /**
1097   * Closes the active SMTP session if one exists.
1098   * @return void
1099   */
1100  public function SmtpClose() {
1101    if ($this->smtp !== null) {
1102      if($this->smtp->Connected()) {
1103        $this->smtp->Quit();
1104        $this->smtp->Close();
1105      }
1106    }
1107  }
1108
1109  /**
1110  * Sets the language for all class error messages.
1111  * Returns false if it cannot load the language file.  The default language is English.
1112  * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
1113  * @param string $lang_path Path to the language file directory
1114   * @return bool
1115  * @access public
1116  */
1117  function SetLanguage($langcode = 'en', $lang_path = 'language/') {
1118    //Define full set of translatable strings
1119    $PHPMAILER_LANG = array(
1120      'authenticate'         => 'SMTP Error: Could not authenticate.',
1121      'connect_host'         => 'SMTP Error: Could not connect to SMTP host.',
1122      'data_not_accepted'    => 'SMTP Error: Data not accepted.',
1123      'empty_message'        => 'Message body empty',
1124      'encoding'             => 'Unknown encoding: ',
1125      'execute'              => 'Could not execute: ',
1126      'file_access'          => 'Could not access file: ',
1127      'file_open'            => 'File Error: Could not open file: ',
1128      'from_failed'          => 'The following From address failed: ',
1129      'instantiate'          => 'Could not instantiate mail function.',
1130      'invalid_address'      => 'Invalid address',
1131      'mailer_not_supported' => ' mailer is not supported.',
1132      'provide_address'      => 'You must provide at least one recipient email address.',
1133      'recipients_failed'    => 'SMTP Error: The following recipients failed: ',
1134      'signing'              => 'Signing Error: ',
1135      'smtp_connect_failed'  => 'SMTP Connect() failed.',
1136      'smtp_error'           => 'SMTP server error: ',
1137      'variable_set'         => 'Cannot set or reset variable: '
1138    );
1139    //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
1140    $l = true;
1141    if ($langcode != 'en') { //There is no English translation file
1142      $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
1143    }
1144    $this->language = $PHPMAILER_LANG;
1145    return ($l == true); //Returns false if language not found
1146  }
1147
1148  /**
1149  * Return the current array of language strings
1150  * @return array
1151  */
1152  public function GetTranslations() {
1153    return $this->language;
1154  }
1155
1156  /////////////////////////////////////////////////
1157  // METHODS, MESSAGE CREATION
1158  /////////////////////////////////////////////////
1159
1160  /**
1161   * Creates recipient headers.
1162   * @access public
1163   * @param string $type
1164   * @param array $addr
1165   * @return string
1166   */
1167  public function AddrAppend($type, $addr) {
1168    $addr_str = $type . ': ';
1169    $addresses = array();
1170    foreach ($addr as $a) {
1171      $addresses[] = $this->AddrFormat($a);
1172    }
1173    $addr_str .= implode(', ', $addresses);
1174    $addr_str .= $this->LE;
1175
1176    return $addr_str;
1177  }
1178
1179  /**
1180   * Formats an address correctly.
1181   * @access public
1182   * @param string $addr
1183   * @return string
1184   */
1185  public function AddrFormat($addr) {
1186    if (empty($addr[1])) {
1187      return $this->SecureHeader($addr[0]);
1188    } else {
1189      return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
1190    }
1191  }
1192
1193  /**
1194   * Wraps message for use with mailers that do not
1195   * automatically perform wrapping and for quoted-printable.
1196   * Original written by philippe.
1197   * @param string $message The message to wrap
1198   * @param integer $length The line length to wrap to
1199   * @param boolean $qp_mode Whether to run in Quoted-Printable mode
1200   * @access public
1201   * @return string
1202   */
1203  public function WrapText($message, $length, $qp_mode = false) {
1204    $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
1205    // If utf-8 encoding is used, we will need to make sure we don't
1206    // split multibyte characters when we wrap
1207    $is_utf8 = (strtolower($this->CharSet) == "utf-8");
1208    $lelen = strlen($this->LE);
1209    $crlflen = strlen(self::CRLF);
1210
1211    $message = $this->FixEOL($message);
1212    if (substr($message, -$lelen) == $this->LE) {
1213      $message = substr($message, 0, -$lelen);
1214    }
1215
1216    $line = explode($this->LE, $message);   // Magic. We know FixEOL uses $LE
1217    $message = '';
1218    for ($i = 0 ;$i < count($line); $i++) {
1219      $line_part = explode(' ', $line[$i]);
1220      $buf = '';
1221      for ($e = 0; $e<count($line_part); $e++) {
1222        $word = $line_part[$e];
1223        if ($qp_mode and (strlen($word) > $length)) {
1224          $space_left = $length - strlen($buf) - $crlflen;
1225          if ($e != 0) {
1226            if ($space_left > 20) {
1227              $len = $space_left;
1228              if ($is_utf8) {
1229                $len = $this->UTF8CharBoundary($word, $len);
1230              } elseif (substr($word, $len - 1, 1) == "=") {
1231                $len--;
1232              } elseif (substr($word, $len - 2, 1) == "=") {
1233                $len -= 2;
1234              }
1235              $part = substr($word, 0, $len);
1236              $word = substr($word, $len);
1237              $buf .= ' ' . $part;
1238              $message .= $buf . sprintf("=%s", self::CRLF);
1239            } else {
1240              $message .= $buf . $soft_break;
1241            }
1242            $buf = '';
1243          }
1244          while (strlen($word) > 0) {
1245            $len = $length;
1246            if ($is_utf8) {
1247              $len = $this->UTF8CharBoundary($word, $len);
1248            } elseif (substr($word, $len - 1, 1) == "=") {
1249              $len--;
1250            } elseif (substr($word, $len - 2, 1) == "=") {
1251              $len -= 2;
1252            }
1253            $part = substr($word, 0, $len);
1254            $word = substr($word, $len);
1255
1256            if (strlen($word) > 0) {
1257              $message .= $part . sprintf("=%s", self::CRLF);
1258            } else {
1259              $buf = $part;
1260            }
1261          }
1262        } else {
1263          $buf_o = $buf;
1264          $buf .= ($e == 0) ? $word : (' ' . $word);
1265
1266          if (strlen($buf) > $length and $buf_o != '') {
1267            $message .= $buf_o . $soft_break;
1268            $buf = $word;
1269          }
1270        }
1271      }
1272      $message .= $buf . self::CRLF;
1273    }
1274
1275    return $message;
1276  }
1277
1278  /**
1279   * Finds last character boundary prior to maxLength in a utf-8
1280   * quoted (printable) encoded string.
1281   * Original written by Colin Brown.
1282   * @access public
1283   * @param string $encodedText utf-8 QP text
1284   * @param int    $maxLength   find last character boundary prior to this length
1285   * @return int
1286   */
1287  public function UTF8CharBoundary($encodedText, $maxLength) {
1288    $foundSplitPos = false;
1289    $lookBack = 3;
1290    while (!$foundSplitPos) {
1291      $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1292      $encodedCharPos = strpos($lastChunk, "=");
1293      if ($encodedCharPos !== false) {
1294        // Found start of encoded character byte within $lookBack block.
1295        // Check the encoded byte value (the 2 chars after the '=')
1296        $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1297        $dec = hexdec($hex);
1298        if ($dec < 128) { // Single byte character.
1299          // If the encoded char was found at pos 0, it will fit
1300          // otherwise reduce maxLength to start of the encoded char
1301          $maxLength = ($encodedCharPos == 0) ? $maxLength :
1302          $maxLength - ($lookBack - $encodedCharPos);
1303          $foundSplitPos = true;
1304        } elseif ($dec >= 192) { // First byte of a multi byte character
1305          // Reduce maxLength to split at start of character
1306          $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1307          $foundSplitPos = true;
1308        } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
1309          $lookBack += 3;
1310        }
1311      } else {
1312        // No encoded character found
1313        $foundSplitPos = true;
1314      }
1315    }
1316    return $maxLength;
1317  }
1318
1319
1320  /**
1321   * Set the body wrapping.
1322   * @access public
1323   * @return void
1324   */
1325  public function SetWordWrap() {
1326    if($this->WordWrap < 1) {
1327      return;
1328    }
1329
1330    switch($this->message_type) {
1331      case 'alt':
1332      case 'alt_inline':
1333      case 'alt_attach':
1334      case 'alt_inline_attach':
1335        $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
1336        break;
1337      default:
1338        $this->Body = $this->WrapText($this->Body, $this->WordWrap);
1339        break;
1340    }
1341  }
1342
1343  /**
1344   * Assembles message header.
1345   * @access public
1346   * @return string The assembled header
1347   */
1348  public function CreateHeader() {
1349    $result = '';
1350
1351    // Set the boundaries
1352    $uniq_id = md5(uniqid(time()));
1353    $this->boundary[1] = 'b1_' . $uniq_id;
1354    $this->boundary[2] = 'b2_' . $uniq_id;
1355    $this->boundary[3] = 'b3_' . $uniq_id;
1356
1357    if ($this->MessageDate == '') {
1358      $result .= $this->HeaderLine('Date', self::RFCDate());
1359    } else {
1360      $result .= $this->HeaderLine('Date', $this->MessageDate);
1361    }
1362
1363    if ($this->ReturnPath) {
1364      $result .= $this->HeaderLine('Return-Path', trim($this->ReturnPath));
1365    } elseif ($this->Sender == '') {
1366      $result .= $this->HeaderLine('Return-Path', trim($this->From));
1367    } else {
1368      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
1369    }
1370
1371    // To be created automatically by mail()
1372    if($this->Mailer != 'mail') {
1373      if ($this->SingleTo === true) {
1374        foreach($this->to as $t) {
1375          $this->SingleToArray[] = $this->AddrFormat($t);
1376        }
1377      } else {
1378        if(count($this->to) > 0) {
1379          $result .= $this->AddrAppend('To', $this->to);
1380        } elseif (count($this->cc) == 0) {
1381          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
1382        }
1383      }
1384    }
1385
1386    $from = array();
1387    $from[0][0] = trim($this->From);
1388    $from[0][1] = $this->FromName;
1389    $result .= $this->AddrAppend('From', $from);
1390
1391    // sendmail and mail() extract Cc from the header before sending
1392    if(count($this->cc) > 0) {
1393      $result .= $this->AddrAppend('Cc', $this->cc);
1394    }
1395
1396    // sendmail and mail() extract Bcc from the header before sending
1397    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
1398      $result .= $this->AddrAppend('Bcc', $this->bcc);
1399    }
1400
1401    if(count($this->ReplyTo) > 0) {
1402      $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
1403    }
1404
1405    // mail() sets the subject itself
1406    if($this->Mailer != 'mail') {
1407      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
1408    }
1409
1410    if($this->MessageID != '') {
1411      $result .= $this->HeaderLine('Message-ID', $this->MessageID);
1412    } else {
1413      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
1414    }
1415    $result .= $this->HeaderLine('X-Priority', $this->Priority);
1416    if ($this->XMailer == '') {
1417        $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
1418    } else {
1419      $myXmailer = trim($this->XMailer);
1420      if ($myXmailer) {
1421        $result .= $this->HeaderLine('X-Mailer', $myXmailer);
1422      }
1423    }
1424
1425    if($this->ConfirmReadingTo != '') {
1426      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
1427    }
1428
1429    // Add custom headers
1430    for($index = 0; $index < count($this->CustomHeader); $index++) {
1431      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
1432    }
1433    if (!$this->sign_key_file) {
1434      $result .= $this->HeaderLine('MIME-Version', '1.0');
1435      $result .= $this->GetMailMIME();
1436    }
1437
1438    return $result;
1439  }
1440
1441  /**
1442   * Returns the message MIME.
1443   * @access public
1444   * @return string
1445   */
1446  public function GetMailMIME() {
1447    $result = '';
1448    switch($this->message_type) {
1449      case 'inline':
1450        $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
1451        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1452        break;
1453      case 'attach':
1454      case 'inline_attach':
1455      case 'alt_attach':
1456      case 'alt_inline_attach':
1457        $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
1458        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1459        break;
1460      case 'alt':
1461      case 'alt_inline':
1462        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1463        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
1464        break;
1465      default:
1466        // Catches case 'plain': and case '':
1467        $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
1468        $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
1469        break;
1470    }
1471
1472    if($this->Mailer != 'mail') {
1473      $result .= $this->LE;
1474    }
1475
1476    return $result;
1477  }
1478
1479  /**
1480   * Returns the MIME message (headers and body). Only really valid post PreSend().
1481   * @access public
1482   * @return string
1483   */
1484  public function GetSentMIMEMessage() {
1485    return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
1486  }
1487
1488
1489  /**
1490   * Assembles the message body.  Returns an empty string on failure.
1491   * @access public
1492   * @throws phpmailerException
1493   * @return string The assembled message body
1494   */
1495  public function CreateBody() {
1496    $body = '';
1497
1498    if ($this->sign_key_file) {
1499      $body .= $this->GetMailMIME().$this->LE;
1500    }
1501
1502    $this->SetWordWrap();
1503
1504    switch($this->message_type) {
1505      case 'inline':
1506        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
1507        $body .= $this->EncodeString($this->Body, $this->Encoding);
1508        $body .= $this->LE.$this->LE;
1509        $body .= $this->AttachAll("inline", $this->boundary[1]);
1510        break;
1511      case 'attach':
1512        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
1513        $body .= $this->EncodeString($this->Body, $this->Encoding);
1514        $body .= $this->LE.$this->LE;
1515        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1516        break;
1517      case 'inline_attach':
1518        $body .= $this->TextLine("--" . $this->boundary[1]);
1519        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1520        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
1521        $body .= $this->LE;
1522        $body .= $this->GetBoundary($this->boundary[2], '', '', '');
1523        $body .= $this->EncodeString($this->Body, $this->Encoding);
1524        $body .= $this->LE.$this->LE;
1525        $body .= $this->AttachAll("inline", $this->boundary[2]);
1526        $body .= $this->LE;
1527        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1528        break;
1529      case 'alt':
1530        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
1531        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1532        $body .= $this->LE.$this->LE;
1533        $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
1534        $body .= $this->EncodeString($this->Body, $this->Encoding);
1535        $body .= $this->LE.$this->LE;
1536        $body .= $this->EndBoundary($this->boundary[1]);
1537        break;
1538      case 'alt_inline':
1539        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
1540        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1541        $body .= $this->LE.$this->LE;
1542        $body .= $this->TextLine("--" . $this->boundary[1]);
1543        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1544        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
1545        $body .= $this->LE;
1546        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
1547        $body .= $this->EncodeString($this->Body, $this->Encoding);
1548        $body .= $this->LE.$this->LE;
1549        $body .= $this->AttachAll("inline", $this->boundary[2]);
1550        $body .= $this->LE;
1551        $body .= $this->EndBoundary($this->boundary[1]);
1552        break;
1553      case 'alt_attach':
1554        $body .= $this->TextLine("--" . $this->boundary[1]);
1555        $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1556        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
1557        $body .= $this->LE;
1558        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
1559        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1560        $body .= $this->LE.$this->LE;
1561        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
1562        $body .= $this->EncodeString($this->Body, $this->Encoding);
1563        $body .= $this->LE.$this->LE;
1564        $body .= $this->EndBoundary($this->boundary[2]);
1565        $body .= $this->LE;
1566        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1567        break;
1568      case 'alt_inline_attach':
1569        $body .= $this->TextLine("--" . $this->boundary[1]);
1570        $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1571        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
1572        $body .= $this->LE;
1573        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
1574        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1575        $body .= $this->LE.$this->LE;
1576        $body .= $this->TextLine("--" . $this->boundary[2]);
1577        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1578        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
1579        $body .= $this->LE;
1580        $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
1581        $body .= $this->EncodeString($this->Body, $this->Encoding);
1582        $body .= $this->LE.$this->LE;
1583        $body .= $this->AttachAll("inline", $this->boundary[3]);
1584        $body .= $this->LE;
1585        $body .= $this->EndBoundary($this->boundary[2]);
1586        $body .= $this->LE;
1587        $body .= $this->AttachAll("attachment", $this->boundary[1]);
1588        break;
1589      default:
1590        // catch case 'plain' and case ''
1591        $body .= $this->EncodeString($this->Body, $this->Encoding);
1592        break;
1593    }
1594
1595    if ($this->IsError()) {
1596      $body = '';
1597    } elseif ($this->sign_key_file) {
1598      try {
1599        $file = tempnam('', 'mail');
1600        file_put_contents($file, $body); //TODO check this worked
1601        $signed = tempnam("", "signed");
1602        if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
1603          @unlink($file);
1604          $body = file_get_contents($signed);
1605          @unlink($signed);
1606        } else {
1607          @unlink($file);
1608          @unlink($signed);
1609          throw new phpmailerException($this->Lang("signing").openssl_error_string());
1610        }
1611      } catch (phpmailerException $e) {
1612        $body = '';
1613        if ($this->exceptions) {
1614          throw $e;
1615        }
1616      }
1617    }
1618
1619    return $body;
1620  }
1621
1622  /**
1623   * Returns the start of a message boundary.
1624   * @access protected
1625   * @param string $boundary
1626   * @param string $charSet
1627   * @param string $contentType
1628   * @param string $encoding
1629   * @return string
1630   */
1631  protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
1632    $result = '';
1633    if($charSet == '') {
1634      $charSet = $this->CharSet;
1635    }
1636    if($contentType == '') {
1637      $contentType = $this->ContentType;
1638    }
1639    if($encoding == '') {
1640      $encoding = $this->Encoding;
1641    }
1642    $result .= $this->TextLine('--' . $boundary);
1643    $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
1644    $result .= $this->LE;
1645    $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
1646    $result .= $this->LE;
1647
1648    return $result;
1649  }
1650
1651  /**
1652   * Returns the end of a message boundary.
1653   * @access protected
1654   * @param string $boundary
1655   * @return string
1656   */
1657  protected function EndBoundary($boundary) {
1658    return $this->LE . '--' . $boundary . '--' . $this->LE;
1659  }
1660
1661  /**
1662   * Sets the message type.
1663   * @access protected
1664   * @return void
1665   */
1666  protected function SetMessageType() {
1667    $this->message_type = array();
1668    if($this->AlternativeExists()) $this->message_type[] = "alt";
1669    if($this->InlineImageExists()) $this->message_type[] = "inline";
1670    if($this->AttachmentExists()) $this->message_type[] = "attach";
1671    $this->message_type = implode("_", $this->message_type);
1672    if($this->message_type == "") $this->message_type = "plain";
1673  }
1674
1675  /**
1676   *  Returns a formatted header line.
1677   * @access public
1678   * @param string $name
1679   * @param string $value
1680   * @return string
1681   */
1682  public function HeaderLine($name, $value) {
1683    return $name . ': ' . $value . $this->LE;
1684  }
1685
1686  /**
1687   * Returns a formatted mail line.
1688   * @access public
1689   * @param string $value
1690   * @return string
1691   */
1692  public function TextLine($value) {
1693    return $value . $this->LE;
1694  }
1695
1696  /////////////////////////////////////////////////
1697  // CLASS METHODS, ATTACHMENTS
1698  /////////////////////////////////////////////////
1699
1700  /**
1701   * Adds an attachment from a path on the filesystem.
1702   * Returns false if the file could not be found
1703   * or accessed.
1704   * @param string $path Path to the attachment.
1705   * @param string $name Overrides the attachment name.
1706   * @param string $encoding File encoding (see $Encoding).
1707   * @param string $type File extension (MIME) type.
1708   * @throws phpmailerException
1709   * @return bool
1710   */
1711  public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
1712    try {
1713      if ( !@is_file($path) ) {
1714        throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
1715      }
1716      $filename = basename($path);
1717      if ( $name == '' ) {
1718        $name = $filename;
1719      }
1720
1721      $this->attachment[] = array(
1722        0 => $path,
1723        1 => $filename,
1724        2 => $name,
1725        3 => $encoding,
1726        4 => $type,
1727        5 => false,  // isStringAttachment
1728        6 => 'attachment',
1729        7 => 0
1730      );
1731
1732    } catch (phpmailerException $e) {
1733      $this->SetError($e->getMessage());
1734      if ($this->exceptions) {
1735        throw $e;
1736      }
1737      if ($this->SMTPDebug) {
1738        $this->edebug($e->getMessage()."\n");
1739      }
1740      if ( $e->getCode() == self::STOP_CRITICAL ) {
1741        return false;
1742      }
1743    }
1744    return true;
1745  }
1746
1747  /**
1748  * Return the current array of attachments
1749  * @return array
1750  */
1751  public function GetAttachments() {
1752    return $this->attachment;
1753  }
1754
1755  /**
1756   * Attaches all fs, string, and binary attachments to the message.
1757   * Returns an empty string on failure.
1758   * @access protected
1759   * @param string $disposition_type
1760   * @param string $boundary
1761   * @return string
1762   */
1763  protected function AttachAll($disposition_type, $boundary) {
1764    // Return text of body
1765    $mime = array();
1766    $cidUniq = array();
1767    $incl = array();
1768
1769    // Add all attachments
1770    foreach ($this->attachment as $attachment) {
1771      // CHECK IF IT IS A VALID DISPOSITION_FILTER
1772      if($attachment[6] == $disposition_type) {
1773        // Check for string attachment
1774        $string = '';
1775        $path = '';
1776        $bString = $attachment[5];
1777        if ($bString) {
1778          $string = $attachment[0];
1779        } else {
1780          $path = $attachment[0];
1781        }
1782
1783        $inclhash = md5(serialize($attachment));
1784        if (in_array($inclhash, $incl)) { continue; }
1785        $incl[]      = $inclhash;
1786        $filename    = $attachment[1];
1787        $name        = $attachment[2];
1788        $encoding    = $attachment[3];
1789        $type        = $attachment[4];
1790        $disposition = $attachment[6];
1791        $cid         = $attachment[7];
1792        if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
1793        $cidUniq[$cid] = true;
1794
1795        $mime[] = sprintf("--%s%s", $boundary, $this->LE);
1796        $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
1797        $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1798
1799        if($disposition == 'inline') {
1800          $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1801        }
1802
1803        $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
1804
1805        // Encode as string attachment
1806        if($bString) {
1807          $mime[] = $this->EncodeString($string, $encoding);
1808          if($this->IsError()) {
1809            return '';
1810          }
1811          $mime[] = $this->LE.$this->LE;
1812        } else {
1813          $mime[] = $this->EncodeFile($path, $encoding);
1814          if($this->IsError()) {
1815            return '';
1816          }
1817          $mime[] = $this->LE.$this->LE;
1818        }
1819      }
1820    }
1821
1822    $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
1823
1824    return implode("", $mime);
1825  }
1826
1827  /**
1828   * Encodes attachment in requested format.
1829   * Returns an empty string on failure.
1830   * @param string $path The full path to the file
1831   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1832   * @throws phpmailerException
1833   * @see EncodeFile()
1834   * @access protected
1835   * @return string
1836   */
1837  protected function EncodeFile($path, $encoding = 'base64') {
1838    try {
1839      if (!is_readable($path)) {
1840        throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
1841      }
1842      //  if (!function_exists('get_magic_quotes')) {
1843      //    function get_magic_quotes() {
1844      //      return false;
1845      //    }
1846      //  }
1847      $magic_quotes = get_magic_quotes_runtime();
1848      if ($magic_quotes) {
1849        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
1850          set_magic_quotes_runtime(0);
1851        } else {
1852          ini_set('magic_quotes_runtime', 0);
1853        }
1854      }
1855      $file_buffer  = file_get_contents($path);
1856      $file_buffer  = $this->EncodeString($file_buffer, $encoding);
1857      if ($magic_quotes) {
1858        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
1859          set_magic_quotes_runtime($magic_quotes);
1860        } else {
1861          ini_set('magic_quotes_runtime', $magic_quotes);
1862        }
1863      }
1864      return $file_buffer;
1865    } catch (Exception $e) {
1866      $this->SetError($e->getMessage());
1867      return '';
1868    }
1869  }
1870
1871  /**
1872   * Encodes string to requested format.
1873   * Returns an empty string on failure.
1874   * @param string $str The text to encode
1875   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1876   * @access public
1877   * @return string
1878   */
1879  public function EncodeString($str, $encoding = 'base64') {
1880    $encoded = '';
1881    switch(strtolower($encoding)) {
1882      case 'base64':
1883        $encoded = chunk_split(base64_encode($str), 76, $this->LE);
1884        break;
1885      case '7bit':
1886      case '8bit':
1887        $encoded = $this->FixEOL($str);
1888        //Make sure it ends with a line break
1889        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
1890          $encoded .= $this->LE;
1891        break;
1892      case 'binary':
1893        $encoded = $str;
1894        break;
1895      case 'quoted-printable':
1896        $encoded = $this->EncodeQP($str);
1897        break;
1898      default:
1899        $this->SetError($this->Lang('encoding') . $encoding);
1900        break;
1901    }
1902    return $encoded;
1903  }
1904
1905  /**
1906   * Encode a header string to best (shortest) of Q, B, quoted or none.
1907   * @access public
1908   * @param string $str
1909   * @param string $position
1910   * @return string
1911   */
1912  public function EncodeHeader($str, $position = 'text') {
1913    $x = 0;
1914
1915    switch (strtolower($position)) {
1916      case 'phrase':
1917        if (!preg_match('/[\200-\377]/', $str)) {
1918          // Can't use addslashes as we don't know what value has magic_quotes_sybase
1919          $encoded = addcslashes($str, "\0..\37\177\\\"");
1920          if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
1921            return ($encoded);
1922          } else {
1923            return ("\"$encoded\"");
1924          }
1925        }
1926        $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
1927        break;
1928      case 'comment':
1929        $x = preg_match_all('/[()"]/', $str, $matches);
1930        // Fall-through
1931      case 'text':
1932      default:
1933        $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
1934        break;
1935    }
1936
1937    if ($x == 0) {
1938      return ($str);
1939    }
1940
1941    $maxlen = 75 - 7 - strlen($this->CharSet);
1942    // Try to select the encoding which should produce the shortest output
1943    if (strlen($str)/3 < $x) {
1944      $encoding = 'B';
1945      if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
1946        // Use a custom function which correctly encodes and wraps long
1947        // multibyte strings without breaking lines within a character
1948        $encoded = $this->Base64EncodeWrapMB($str, "\n");
1949      } else {
1950        $encoded = base64_encode($str);
1951        $maxlen -= $maxlen % 4;
1952        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
1953      }
1954    } else {
1955      $encoding = 'Q';
1956      $encoded = $this->EncodeQ($str, $position);
1957      $encoded = $this->WrapText($encoded, $maxlen, true);
1958      $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
1959    }
1960
1961    $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
1962    $encoded = trim(str_replace("\n", $this->LE, $encoded));
1963
1964    return $encoded;
1965  }
1966
1967  /**
1968   * Checks if a string contains multibyte characters.
1969   * @access public
1970   * @param string $str multi-byte text to wrap encode
1971   * @return bool
1972   */
1973  public function HasMultiBytes($str) {
1974    if (function_exists('mb_strlen')) {
1975      return (strlen($str) > mb_strlen($str, $this->CharSet));
1976    } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
1977      return false;
1978    }
1979  }
1980
1981  /**
1982   * Correctly encodes and wraps long multibyte strings for mail headers
1983   * without breaking lines within a character.
1984   * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
1985   * @access public
1986   * @param string $str multi-byte text to wrap encode
1987   * @param string $lf string to use as linefeed/end-of-line
1988   * @return string
1989   */
1990  public function Base64EncodeWrapMB($str, $lf=null) {
1991    $start = "=?".$this->CharSet."?B?";
1992    $end = "?=";
1993    $encoded = "";
1994    if ($lf === null) {
1995      $lf = $this->LE;
1996    }
1997
1998    $mb_length = mb_strlen($str, $this->CharSet);
1999    // Each line must have length <= 75, including $start and $end
2000    $length = 75 - strlen($start) - strlen($end);
2001    // Average multi-byte ratio
2002    $ratio = $mb_length / strlen($str);
2003    // Base64 has a 4:3 ratio
2004    $offset = $avgLength = floor($length * $ratio * .75);
2005
2006    for ($i = 0; $i < $mb_length; $i += $offset) {
2007      $lookBack = 0;
2008
2009      do {
2010        $offset = $avgLength - $lookBack;
2011        $chunk = mb_substr($str, $i, $offset, $this->CharSet);
2012        $chunk = base64_encode($chunk);
2013        $lookBack++;
2014      }
2015      while (strlen($chunk) > $length);
2016
2017      $encoded .= $chunk . $lf;
2018    }
2019
2020    // Chomp the last linefeed
2021    $encoded = substr($encoded, 0, -strlen($lf));
2022    return $encoded;
2023  }
2024
2025  /**
2026  * Encode string to quoted-printable.
2027  * Only uses standard PHP, slow, but will always work
2028  * @access public
2029   * @param string $input
2030  * @param integer $line_max Number of chars allowed on a line before wrapping
2031   * @param bool $space_conv
2032   * @internal param string $string the text to encode
2033  * @return string
2034  */
2035  public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
2036    $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
2037    $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
2038    $eol = "\r\n";
2039    $escape = '=';
2040    $output = '';
2041    while( list(, $line) = each($lines) ) {
2042      $linlen = strlen($line);
2043      $newline = '';
2044      for($i = 0; $i < $linlen; $i++) {
2045        $c = substr( $line, $i, 1 );
2046        $dec = ord( $c );
2047        if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
2048          $c = '=2E';
2049        }
2050        if ( $dec == 32 ) {
2051          if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
2052            $c = '=20';
2053          } else if ( $space_conv ) {
2054            $c = '=20';
2055          }
2056        } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
2057          $h2 = (integer)floor($dec/16);
2058          $h1 = (integer)floor($dec%16);
2059          $c = $escape.$hex[$h2].$hex[$h1];
2060        }
2061        if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
2062          $output .= $newline.$escape.$eol; //  soft line break; " =\r\n" is okay
2063          $newline = '';
2064          // check if newline first character will be point or not
2065          if ( $dec == 46 ) {
2066            $c = '=2E';
2067          }
2068        }
2069        $newline .= $c;
2070      } // end of for
2071      $output .= $newline.$eol;
2072    } // end of while
2073    return $output;
2074  }
2075
2076  /**
2077  * Encode string to RFC2045 (6.7) quoted-printable format
2078  * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
2079  * Also results in same content as you started with after decoding
2080  * @see EncodeQPphp()
2081  * @access public
2082  * @param string $string the text to encode
2083  * @param integer $line_max Number of chars allowed on a line before wrapping
2084  * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
2085  * @return string
2086  * @author Marcus Bointon
2087  */
2088  public function EncodeQP($string, $line_max = 76, $space_conv = false) {
2089    if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
2090      return quoted_printable_encode($string);
2091    }
2092    $filters = stream_get_filters();
2093    if (!in_array('convert.*', $filters)) { //Got convert stream filter?
2094      return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
2095    }
2096    $fp = fopen('php://temp/', 'r+');
2097    $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
2098    $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
2099    $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
2100    fputs($fp, $string);
2101    rewind($fp);
2102    $out = stream_get_contents($fp);
2103    stream_filter_remove($s);
2104    $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
2105    fclose($fp);
2106    return $out;
2107  }
2108
2109  /**
2110   * Encode string to q encoding.
2111   * @link http://tools.ietf.org/html/rfc2047
2112   * @param string $str the text to encode
2113   * @param string $position Where the text is going to be used, see the RFC for what that means
2114   * @access public
2115   * @return string
2116   */
2117  public function EncodeQ($str, $position = 'text') {
2118    //There should not be any EOL in the string
2119	$pattern="";
2120    $encoded = str_replace(array("\r", "\n"), '', $str);
2121    switch (strtolower($position)) {
2122      case 'phrase':
2123        $pattern = '^A-Za-z0-9!*+\/ -';
2124        break;
2125
2126      case 'comment':
2127        $pattern = '\(\)"';
2128        //note that we dont break here!
2129        //for this reason we build the $pattern withoud including delimiters and []
2130
2131      case 'text':
2132      default:
2133        //Replace every high ascii, control =, ? and _ characters
2134        //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
2135        $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
2136        break;
2137    }
2138
2139    if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
2140      foreach (array_unique($matches[0]) as $char) {
2141        $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
2142      }
2143    }
2144
2145    //Replace every spaces to _ (more readable than =20)
2146    return str_replace(' ', '_', $encoded);
2147}
2148
2149
2150  /**
2151   * Adds a string or binary attachment (non-filesystem) to the list.
2152   * This method can be used to attach ascii or binary data,
2153   * such as a BLOB record from a database.
2154   * @param string $string String attachment data.
2155   * @param string $filename Name of the attachment.
2156   * @param string $encoding File encoding (see $Encoding).
2157   * @param string $type File extension (MIME) type.
2158   * @return void
2159   */
2160  public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
2161    // Append to $attachment array
2162    $this->attachment[] = array(
2163      0 => $string,
2164      1 => $filename,
2165      2 => basename($filename),
2166      3 => $encoding,
2167      4 => $type,
2168      5 => true,  // isStringAttachment
2169      6 => 'attachment',
2170      7 => 0
2171    );
2172  }
2173
2174  /**
2175   * Adds an embedded attachment.  This can include images, sounds, and
2176   * just about any other document.  Make sure to set the $type to an
2177   * image type.  For JPEG images use "image/jpeg" and for GIF images
2178   * use "image/gif".
2179   * @param string $path Path to the attachment.
2180   * @param string $cid Content ID of the attachment.  Use this to identify
2181   *        the Id for accessing the image in an HTML form.
2182   * @param string $name Overrides the attachment name.
2183   * @param string $encoding File encoding (see $Encoding).
2184   * @param string $type File extension (MIME) type.
2185   * @return bool
2186   */
2187  public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
2188
2189    if ( !@is_file($path) ) {
2190      $this->SetError($this->Lang('file_access') . $path);
2191      return false;
2192    }
2193
2194    $filename = basename($path);
2195    if ( $name == '' ) {
2196      $name = $filename;
2197    }
2198
2199    // Append to $attachment array
2200    $this->attachment[] = array(
2201      0 => $path,
2202      1 => $filename,
2203      2 => $name,
2204      3 => $encoding,
2205      4 => $type,
2206      5 => false,  // isStringAttachment
2207      6 => 'inline',
2208      7 => $cid
2209    );
2210
2211    return true;
2212  }
2213
2214  /**
2215   * Adds an embedded stringified attachment.  This can include images, sounds, and
2216   * just about any other document.  Make sure to set the $type to an
2217   * image type.  For JPEG images use "image/jpeg" and for GIF images
2218   * use "image/gif".
2219   * @param string $string The attachment.
2220   * @param string $cid Content ID of the attachment.  Use this to identify
2221   *        the Id for accessing the image in an HTML form.
2222   * @param string $name Overrides the attachment name.
2223   * @param string $encoding File encoding (see $Encoding).
2224   * @param string $type File extension (MIME) type.
2225   * @return bool
2226   */
2227  public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
2228    // Append to $attachment array
2229    $this->attachment[] = array(
2230      0 => $string,
2231      1 => $name,
2232      2 => $name,
2233      3 => $encoding,
2234      4 => $type,
2235      5 => true,  // isStringAttachment
2236      6 => 'inline',
2237      7 => $cid
2238    );
2239  }
2240
2241  /**
2242   * Returns true if an inline attachment is present.
2243   * @access public
2244   * @return bool
2245   */
2246  public function InlineImageExists() {
2247    foreach($this->attachment as $attachment) {
2248      if ($attachment[6] == 'inline') {
2249        return true;
2250      }
2251    }
2252    return false;
2253  }
2254
2255  /**
2256   * Returns true if an attachment (non-inline) is present.
2257   * @return bool
2258   */
2259  public function AttachmentExists() {
2260    foreach($this->attachment as $attachment) {
2261      if ($attachment[6] == 'attachment') {
2262        return true;
2263      }
2264    }
2265    return false;
2266  }
2267
2268  /**
2269   * Does this message have an alternative body set?
2270   * @return bool
2271   */
2272  public function AlternativeExists() {
2273    return !empty($this->AltBody);
2274  }
2275
2276  /////////////////////////////////////////////////
2277  // CLASS METHODS, MESSAGE RESET
2278  /////////////////////////////////////////////////
2279
2280  /**
2281   * Clears all recipients assigned in the TO array.  Returns void.
2282   * @return void
2283   */
2284  public function ClearAddresses() {
2285    foreach($this->to as $to) {
2286      unset($this->all_recipients[strtolower($to[0])]);
2287    }
2288    $this->to = array();
2289  }
2290
2291  /**
2292   * Clears all recipients assigned in the CC array.  Returns void.
2293   * @return void
2294   */
2295  public function ClearCCs() {
2296    foreach($this->cc as $cc) {
2297      unset($this->all_recipients[strtolower($cc[0])]);
2298    }
2299    $this->cc = array();
2300  }
2301
2302  /**
2303   * Clears all recipients assigned in the BCC array.  Returns void.
2304   * @return void
2305   */
2306  public function ClearBCCs() {
2307    foreach($this->bcc as $bcc) {
2308      unset($this->all_recipients[strtolower($bcc[0])]);
2309    }
2310    $this->bcc = array();
2311  }
2312
2313  /**
2314   * Clears all recipients assigned in the ReplyTo array.  Returns void.
2315   * @return void
2316   */
2317  public function ClearReplyTos() {
2318    $this->ReplyTo = array();
2319  }
2320
2321  /**
2322   * Clears all recipients assigned in the TO, CC and BCC
2323   * array.  Returns void.
2324   * @return void
2325   */
2326  public function ClearAllRecipients() {
2327    $this->to = array();
2328    $this->cc = array();
2329    $this->bcc = array();
2330    $this->all_recipients = array();
2331  }
2332
2333  /**
2334   * Clears all previously set filesystem, string, and binary
2335   * attachments.  Returns void.
2336   * @return void
2337   */
2338  public function ClearAttachments() {
2339    $this->attachment = array();
2340  }
2341
2342  /**
2343   * Clears all custom headers.  Returns void.
2344   * @return void
2345   */
2346  public function ClearCustomHeaders() {
2347    $this->CustomHeader = array();
2348  }
2349
2350  /////////////////////////////////////////////////
2351  // CLASS METHODS, MISCELLANEOUS
2352  /////////////////////////////////////////////////
2353
2354  /**
2355   * Adds the error message to the error container.
2356   * @access protected
2357   * @param string $msg
2358   * @return void
2359   */
2360  protected function SetError($msg) {
2361    $this->error_count++;
2362    if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
2363      $lasterror = $this->smtp->getError();
2364      if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
2365        $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
2366      }
2367    }
2368    $this->ErrorInfo = $msg;
2369  }
2370
2371  /**
2372   * Returns the proper RFC 822 formatted date.
2373   * @access public
2374   * @return string
2375   * @static
2376   */
2377  public static function RFCDate() {
2378    $tz = date('Z');
2379    $tzs = ($tz < 0) ? '-' : '+';
2380    $tz = abs($tz);
2381    $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
2382    $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
2383
2384    return $result;
2385  }
2386
2387  /**
2388   * Returns the server hostname or 'localhost.localdomain' if unknown.
2389   * @access protected
2390   * @return string
2391   */
2392  protected function ServerHostname() {
2393    if (!empty($this->Hostname)) {
2394      $result = $this->Hostname;
2395    } elseif (isset($_SERVER['SERVER_NAME'])) {
2396      $result = $_SERVER['SERVER_NAME'];
2397    } else {
2398      $result = 'localhost.localdomain';
2399    }
2400
2401    return $result;
2402  }
2403
2404  /**
2405   * Returns a message in the appropriate language.
2406   * @access protected
2407   * @param string $key
2408   * @return string
2409   */
2410  protected function Lang($key) {
2411    if(count($this->language) < 1) {
2412      $this->SetLanguage('en'); // set the default language
2413    }
2414
2415    if(isset($this->language[$key])) {
2416      return $this->language[$key];
2417    } else {
2418      return 'Language string failed to load: ' . $key;
2419    }
2420  }
2421
2422  /**
2423   * Returns true if an error occurred.
2424   * @access public
2425   * @return bool
2426   */
2427  public function IsError() {
2428    return ($this->error_count > 0);
2429  }
2430
2431  /**
2432   * Changes every end of line from CRLF, CR or LF to $this->LE.
2433   * @access public
2434   * @param string $str String to FixEOL
2435   * @return string
2436   */
2437  public function FixEOL($str) {
2438	// condense down to \n
2439	$nstr = str_replace(array("\r\n", "\r"), "\n", $str);
2440	// Now convert LE as needed
2441	if ($this->LE !== "\n") {
2442		$nstr = str_replace("\n", $this->LE, $nstr);
2443	}
2444    return  $nstr;
2445  }
2446
2447  /**
2448   * Adds a custom header. $name value can be overloaded to contain
2449   * both header name and value (name:value)
2450   * @access public
2451   * @param string $name custom header name
2452   * @param string $value header value
2453   * @return void
2454   */
2455  public function AddCustomHeader($name, $value=null) {
2456	if ($value === null) {
2457		// Value passed in as name:value
2458		$this->CustomHeader[] = explode(':', $name, 2);
2459	} else {
2460		$this->CustomHeader[] = array($name, $value);
2461	}
2462  }
2463
2464  /**
2465   * Evaluates the message and returns modifications for inline images and backgrounds
2466   * @access public
2467   * @param string $message Text to be HTML modified
2468   * @param string $basedir baseline directory for path
2469   * @return string $message
2470   */
2471  public function MsgHTML($message, $basedir = '') {
2472    preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
2473    if(isset($images[2])) {
2474      foreach($images[2] as $i => $url) {
2475        // do not change urls for absolute images (thanks to corvuscorax)
2476        if (!preg_match('#^[A-z]+://#', $url)) {
2477          $filename = basename($url);
2478          $directory = dirname($url);
2479          if ($directory == '.') {
2480            $directory = '';
2481          }
2482          $cid = 'cid:' . md5($filename);
2483          $ext = pathinfo($filename, PATHINFO_EXTENSION);
2484          $mimeType  = self::_mime_types($ext);
2485          if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; }
2486          if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
2487          if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType) ) {
2488            $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"".$cid."\"", $message);
2489          }
2490        }
2491      }
2492    }
2493    $this->IsHTML(true);
2494    $this->Body = $message;
2495    if (empty($this->AltBody)) {
2496        $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
2497        if (!empty($textMsg)) {
2498            $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet);
2499        }
2500    }
2501    if (empty($this->AltBody)) {
2502      $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
2503    }
2504    return $message;
2505  }
2506
2507  /**
2508   * Gets the MIME type of the embedded or inline image
2509   * @param string $ext File extension
2510   * @access public
2511   * @return string MIME type of ext
2512   * @static
2513   */
2514  public static function _mime_types($ext = '') {
2515    $mimes = array(
2516      'xl'    =>  'application/excel',
2517      'hqx'   =>  'application/mac-binhex40',
2518      'cpt'   =>  'application/mac-compactpro',
2519      'bin'   =>  'application/macbinary',
2520      'doc'   =>  'application/msword',
2521      'word'  =>  'application/msword',
2522      'class' =>  'application/octet-stream',
2523      'dll'   =>  'application/octet-stream',
2524      'dms'   =>  'application/octet-stream',
2525      'exe'   =>  'application/octet-stream',
2526      'lha'   =>  'application/octet-stream',
2527      'lzh'   =>  'application/octet-stream',
2528      'psd'   =>  'application/octet-stream',
2529      'sea'   =>  'application/octet-stream',
2530      'so'    =>  'application/octet-stream',
2531      'oda'   =>  'application/oda',
2532      'pdf'   =>  'application/pdf',
2533      'ai'    =>  'application/postscript',
2534      'eps'   =>  'application/postscript',
2535      'ps'    =>  'application/postscript',
2536      'smi'   =>  'application/smil',
2537      'smil'  =>  'application/smil',
2538      'mif'   =>  'application/vnd.mif',
2539      'xls'   =>  'application/vnd.ms-excel',
2540      'ppt'   =>  'application/vnd.ms-powerpoint',
2541      'wbxml' =>  'application/vnd.wap.wbxml',
2542      'wmlc'  =>  'application/vnd.wap.wmlc',
2543      'dcr'   =>  'application/x-director',
2544      'dir'   =>  'application/x-director',
2545      'dxr'   =>  'application/x-director',
2546      'dvi'   =>  'application/x-dvi',
2547      'gtar'  =>  'application/x-gtar',
2548      'php3'  =>  'application/x-httpd-php',
2549      'php4'  =>  'application/x-httpd-php',
2550      'php'   =>  'application/x-httpd-php',
2551      'phtml' =>  'application/x-httpd-php',
2552      'phps'  =>  'application/x-httpd-php-source',
2553      'js'    =>  'application/x-javascript',
2554      'swf'   =>  'application/x-shockwave-flash',
2555      'sit'   =>  'application/x-stuffit',
2556      'tar'   =>  'application/x-tar',
2557      'tgz'   =>  'application/x-tar',
2558      'xht'   =>  'application/xhtml+xml',
2559      'xhtml' =>  'application/xhtml+xml',
2560      'zip'   =>  'application/zip',
2561      'mid'   =>  'audio/midi',
2562      'midi'  =>  'audio/midi',
2563      'mp2'   =>  'audio/mpeg',
2564      'mp3'   =>  'audio/mpeg',
2565      'mpga'  =>  'audio/mpeg',
2566      'aif'   =>  'audio/x-aiff',
2567      'aifc'  =>  'audio/x-aiff',
2568      'aiff'  =>  'audio/x-aiff',
2569      'ram'   =>  'audio/x-pn-realaudio',
2570      'rm'    =>  'audio/x-pn-realaudio',
2571      'rpm'   =>  'audio/x-pn-realaudio-plugin',
2572      'ra'    =>  'audio/x-realaudio',
2573      'wav'   =>  'audio/x-wav',
2574      'bmp'   =>  'image/bmp',
2575      'gif'   =>  'image/gif',
2576      'jpeg'  =>  'image/jpeg',
2577      'jpe'   =>  'image/jpeg',
2578      'jpg'   =>  'image/jpeg',
2579      'png'   =>  'image/png',
2580      'tiff'  =>  'image/tiff',
2581      'tif'   =>  'image/tiff',
2582      'eml'   =>  'message/rfc822',
2583      'css'   =>  'text/css',
2584      'html'  =>  'text/html',
2585      'htm'   =>  'text/html',
2586      'shtml' =>  'text/html',
2587      'log'   =>  'text/plain',
2588      'text'  =>  'text/plain',
2589      'txt'   =>  'text/plain',
2590      'rtx'   =>  'text/richtext',
2591      'rtf'   =>  'text/rtf',
2592      'xml'   =>  'text/xml',
2593      'xsl'   =>  'text/xml',
2594      'mpeg'  =>  'video/mpeg',
2595      'mpe'   =>  'video/mpeg',
2596      'mpg'   =>  'video/mpeg',
2597      'mov'   =>  'video/quicktime',
2598      'qt'    =>  'video/quicktime',
2599      'rv'    =>  'video/vnd.rn-realvideo',
2600      'avi'   =>  'video/x-msvideo',
2601      'movie' =>  'video/x-sgi-movie'
2602    );
2603    return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
2604  }
2605
2606  /**
2607  * Set (or reset) Class Objects (variables)
2608  *
2609  * Usage Example:
2610  * $page->set('X-Priority', '3');
2611  *
2612  * @access public
2613  * @param string $name Parameter Name
2614  * @param mixed $value Parameter Value
2615  * NOTE: will not work with arrays, there are no arrays to set/reset
2616   * @throws phpmailerException
2617   * @return bool
2618  * @todo Should this not be using __set() magic function?
2619  */
2620  public function set($name, $value = '') {
2621    try {
2622      if (isset($this->$name) ) {
2623        $this->$name = $value;
2624      } else {
2625        throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
2626      }
2627    } catch (Exception $e) {
2628      $this->SetError($e->getMessage());
2629      if ($e->getCode() == self::STOP_CRITICAL) {
2630        return false;
2631      }
2632    }
2633    return true;
2634  }
2635
2636  /**
2637   * Strips newlines to prevent header injection.
2638   * @access public
2639   * @param string $str String
2640   * @return string
2641   */
2642  public function SecureHeader($str) {
2643    return trim(str_replace(array("\r", "\n"), '', $str));
2644  }
2645
2646  /**
2647   * Set the private key file and password to sign the message.
2648   *
2649   * @access public
2650   * @param $cert_filename
2651   * @param string $key_filename Parameter File Name
2652   * @param string $key_pass Password for private key
2653   */
2654  public function Sign($cert_filename, $key_filename, $key_pass) {
2655    $this->sign_cert_file = $cert_filename;
2656    $this->sign_key_file = $key_filename;
2657    $this->sign_key_pass = $key_pass;
2658  }
2659
2660  /**
2661   * Set the private key file and password to sign the message.
2662   *
2663   * @access public
2664   * @param string $txt
2665   * @return string
2666   */
2667  public function DKIM_QP($txt) {
2668    $line = '';
2669    for ($i = 0; $i < strlen($txt); $i++) {
2670      $ord = ord($txt[$i]);
2671      if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
2672        $line .= $txt[$i];
2673      } else {
2674        $line .= "=".sprintf("%02X", $ord);
2675      }
2676    }
2677    return $line;
2678  }
2679
2680  /**
2681   * Generate DKIM signature
2682   *
2683   * @access public
2684   * @param string $s Header
2685   * @return string
2686   */
2687  public function DKIM_Sign($s) {
2688    $privKeyStr = file_get_contents($this->DKIM_private);
2689    if ($this->DKIM_passphrase != '') {
2690      $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
2691    } else {
2692      $privKey = $privKeyStr;
2693    }
2694    if (openssl_sign($s, $signature, $privKey)) {
2695      return base64_encode($signature);
2696    }
2697    return '';
2698  }
2699
2700  /**
2701   * Generate DKIM Canonicalization Header
2702   *
2703   * @access public
2704   * @param string $s Header
2705   * @return string
2706   */
2707  public function DKIM_HeaderC($s) {
2708    $s = preg_replace("/\r\n\s+/", " ", $s);
2709    $lines = explode("\r\n", $s);
2710    foreach ($lines as $key => $line) {
2711      list($heading, $value) = explode(":", $line, 2);
2712      $heading = strtolower($heading);
2713      $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
2714      $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
2715    }
2716    $s = implode("\r\n", $lines);
2717    return $s;
2718  }
2719
2720  /**
2721   * Generate DKIM Canonicalization Body
2722   *
2723   * @access public
2724   * @param string $body Message Body
2725   * @return string
2726   */
2727  public function DKIM_BodyC($body) {
2728    if ($body == '') return "\r\n";
2729    // stabilize line endings
2730    $body = str_replace("\r\n", "\n", $body);
2731    $body = str_replace("\n", "\r\n", $body);
2732    // END stabilize line endings
2733    while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
2734      $body = substr($body, 0, strlen($body) - 2);
2735    }
2736    return $body;
2737  }
2738
2739  /**
2740   * Create the DKIM header, body, as new header
2741   *
2742   * @access public
2743   * @param string $headers_line Header lines
2744   * @param string $subject Subject
2745   * @param string $body Body
2746   * @return string
2747   */
2748  public function DKIM_Add($headers_line, $subject, $body) {
2749    $DKIMsignatureType    = 'rsa-sha1'; // Signature & hash algorithms
2750    $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
2751    $DKIMquery            = 'dns/txt'; // Query method
2752    $DKIMtime             = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
2753    $subject_header       = "Subject: $subject";
2754    $headers              = explode($this->LE, $headers_line);
2755	$from_header          = "";
2756	$to_header            = "";
2757    foreach($headers as $header) {
2758      if (strpos($header, 'From:') === 0) {
2759        $from_header = $header;
2760      } elseif (strpos($header, 'To:') === 0) {
2761        $to_header = $header;
2762      }
2763    }
2764    $from     = str_replace('|', '=7C', $this->DKIM_QP($from_header));
2765    $to       = str_replace('|', '=7C', $this->DKIM_QP($to_header));
2766    $subject  = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
2767    $body     = $this->DKIM_BodyC($body);
2768    $DKIMlen  = strlen($body) ; // Length of body
2769    $DKIMb64  = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
2770    $ident    = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
2771    $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
2772                "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
2773                "\th=From:To:Subject;\r\n".
2774                "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
2775                "\tz=$from\r\n".
2776                "\t|$to\r\n".
2777                "\t|$subject;\r\n".
2778                "\tbh=" . $DKIMb64 . ";\r\n".
2779                "\tb=";
2780    $toSign   = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
2781    $signed   = $this->DKIM_Sign($toSign);
2782    return "X-PHPMAILER-DKIM: code.google.com/a/apache-extras.org/p/phpmailer/\r\n".$dkimhdrs.$signed."\r\n";
2783  }
2784
2785  /**
2786   * Perform callback
2787   * @param boolean $isSent
2788   * @param string $to
2789   * @param string $cc
2790   * @param string $bcc
2791   * @param string $subject
2792   * @param string $body
2793   * @param string $from
2794   */
2795  protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from=null) {
2796    if (!empty($this->action_function) && is_callable($this->action_function)) {
2797      $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
2798      call_user_func_array($this->action_function, $params);
2799    }
2800  }
2801}
2802
2803/**
2804 * Exception handler for PHPMailer
2805 * @package PHPMailer
2806 */
2807class phpmailerException extends Exception {
2808  /**
2809   * Prettify error message output
2810   * @return string
2811   */
2812  public function errorMessage() {
2813    $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
2814    return $errorMsg;
2815  }
2816}
2817?>