Commit d75baf0ce6981df27868a3dfc0e23b551909402d

Authored by root
1 parent 80fb6f43

add bouncer

Too many changes to show.

To preserve performance only 29 of 29+ files are displayed.

  1 +before_commands:
  2 + - "composer install --prefer-source"
  3 +
  4 +tools:
  5 + # Code Coverage
  6 + external_code_coverage:
  7 + enabled: true
  8 + timeout: 300
  9 + filter:
  10 + excluded_paths:
  11 + - 'docs/*'
  12 + - 'examples/*'
  13 + - 'extras/*'
  14 + - 'test/*'
  15 + - 'vendor/*'
  16 +
  17 +
  18 + php_code_coverage:
  19 + enabled: false
  20 + test_command: phpunit
  21 + filter:
  22 + excluded_paths:
  23 + - 'docs/*'
  24 + - 'examples/*'
  25 + - 'extras/*'
  26 + - 'test/*'
  27 + - 'vendor/*'
  28 +
  29 +
  30 + # Code Sniffer
  31 + php_code_sniffer:
  32 + enabled: true
  33 + command: phpcs
  34 + config:
  35 + standard: PSR2
  36 + filter:
  37 + excluded_paths:
  38 + - 'docs/*'
  39 + - 'examples/*'
  40 + - 'extras/*'
  41 + - 'test/*'
  42 + - 'vendor/*'
  43 +
  44 +
  45 + # Copy/Paste Detector
  46 + php_cpd:
  47 + enabled: true
  48 + command: phpcpd
  49 + excluded_dirs:
  50 + - docs
  51 + - examples
  52 + - extras
  53 + - test
  54 + - vendor
  55 +
  56 +
  57 + # PHP CS Fixer (http://http://cs.sensiolabs.org/).
  58 + php_cs_fixer:
  59 + enabled: true
  60 + command: php-cs-fixer
  61 + config:
  62 + level: psr2
  63 + filter:
  64 + excluded_paths:
  65 + - 'docs/*'
  66 + - 'examples/*'
  67 + - 'extras/*'
  68 + - 'test/*'
  69 + - 'vendor/*'
  70 +
  71 +
  72 + # Analyzes the size and structure of a PHP project.
  73 + php_loc:
  74 + enabled: true
  75 + command: phploc
  76 + excluded_dirs:
  77 + - docs
  78 + - examples
  79 + - extras
  80 + - test
  81 + - vendor
  82 +
  83 +
  84 + # PHP Mess Detector (http://phpmd.org).
  85 + php_mess_detector:
  86 + enabled: true
  87 + command: phpmd
  88 + config:
  89 + rulesets:
  90 + - codesize
  91 + - unusedcode
  92 + - naming
  93 + - design
  94 + filter:
  95 + excluded_paths:
  96 + - 'docs/*'
  97 + - 'examples/*'
  98 + - 'extras/*'
  99 + - 'test/*'
  100 + - 'vendor/*'
  101 +
  102 +
  103 + # Analyzes the size and structure of a PHP project.
  104 + php_pdepend:
  105 + enabled: true
  106 + command: pdepend
  107 + excluded_dirs:
  108 + - docs
  109 + - examples
  110 + - extras
  111 + - test
  112 + - vendor
  113 +
  114 + # Runs Scrutinizer's PHP Analyzer Tool
  115 + php_analyzer:
  116 + enabled: true
  117 + filter:
  118 + excluded_paths:
  119 + - 'docs/*'
  120 + - 'examples/*'
  121 + - 'extras/*'
  122 + - 'test/*'
  123 + - 'vendor/*'
  124 +
  125 + # Security Advisory Checker
  126 + sensiolabs_security_checker: true
... ...
  1 +language: php
  2 +php:
  3 + - 5.5
  4 + - 5.4
  5 + - 5.3
  6 +before_install:
  7 + - sudo apt-get update -qq
  8 + - sudo apt-get install -y -qq postfix
  9 +before_script:
  10 + - sudo service postfix stop
  11 + - smtp-sink -d "%d.%H.%M.%S" localhost:2500 1000 &
  12 + - mkdir -p build/logs
  13 + - cd test
  14 + - cp testbootstrap-dist.php testbootstrap.php
  15 + - chmod +x fakesendmail.sh
  16 + - sudo mkdir -p /var/qmail/bin
  17 + - sudo cp fakesendmail.sh /var/qmail/bin/sendmail
  18 + - sudo cp fakesendmail.sh /usr/sbin/sendmail
  19 + - echo 'sendmail_path = "/usr/sbin/sendmail -t -i "' | sudo tee "/home/travis/.phpenv/versions/`php -i|grep "PHP Version"|head -n 1|grep -o -P '\d+\.\d+\.\d+.*'`/etc/conf.d/sendmail.ini"
  20 + - pwd
  21 + - ls -al
  22 +script:
  23 + - phpunit --configuration ../travis.phpunit.xml.dist
  24 +after_script:
  25 + - wget https://scrutinizer-ci.com/ocular.phar
  26 + - php ocular.phar code-coverage:upload --format=php-clover ../build/logs/clover.xml
... ...
  1 + GNU LESSER GENERAL PUBLIC LICENSE
  2 + Version 2.1, February 1999
  3 +
  4 + Copyright (C) 1991, 1999 Free Software Foundation, Inc.
  5 + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  6 + Everyone is permitted to copy and distribute verbatim copies
  7 + of this license document, but changing it is not allowed.
  8 +
  9 +[This is the first released version of the Lesser GPL. It also counts
  10 + as the successor of the GNU Library Public License, version 2, hence
  11 + the version number 2.1.]
  12 +
  13 + Preamble
  14 +
  15 + The licenses for most software are designed to take away your
  16 +freedom to share and change it. By contrast, the GNU General Public
  17 +Licenses are intended to guarantee your freedom to share and change
  18 +free software--to make sure the software is free for all its users.
  19 +
  20 + This license, the Lesser General Public License, applies to some
  21 +specially designated software packages--typically libraries--of the
  22 +Free Software Foundation and other authors who decide to use it. You
  23 +can use it too, but we suggest you first think carefully about whether
  24 +this license or the ordinary General Public License is the better
  25 +strategy to use in any particular case, based on the explanations below.
  26 +
  27 + When we speak of free software, we are referring to freedom of use,
  28 +not price. Our General Public Licenses are designed to make sure that
  29 +you have the freedom to distribute copies of free software (and charge
  30 +for this service if you wish); that you receive source code or can get
  31 +it if you want it; that you can change the software and use pieces of
  32 +it in new free programs; and that you are informed that you can do
  33 +these things.
  34 +
  35 + To protect your rights, we need to make restrictions that forbid
  36 +distributors to deny you these rights or to ask you to surrender these
  37 +rights. These restrictions translate to certain responsibilities for
  38 +you if you distribute copies of the library or if you modify it.
  39 +
  40 + For example, if you distribute copies of the library, whether gratis
  41 +or for a fee, you must give the recipients all the rights that we gave
  42 +you. You must make sure that they, too, receive or can get the source
  43 +code. If you link other code with the library, you must provide
  44 +complete object files to the recipients, so that they can relink them
  45 +with the library after making changes to the library and recompiling
  46 +it. And you must show them these terms so they know their rights.
  47 +
  48 + We protect your rights with a two-step method: (1) we copyright the
  49 +library, and (2) we offer you this license, which gives you legal
  50 +permission to copy, distribute and/or modify the library.
  51 +
  52 + To protect each distributor, we want to make it very clear that
  53 +there is no warranty for the free library. Also, if the library is
  54 +modified by someone else and passed on, the recipients should know
  55 +that what they have is not the original version, so that the original
  56 +author's reputation will not be affected by problems that might be
  57 +introduced by others.
  58 +
  59 + Finally, software patents pose a constant threat to the existence of
  60 +any free program. We wish to make sure that a company cannot
  61 +effectively restrict the users of a free program by obtaining a
  62 +restrictive license from a patent holder. Therefore, we insist that
  63 +any patent license obtained for a version of the library must be
  64 +consistent with the full freedom of use specified in this license.
  65 +
  66 + Most GNU software, including some libraries, is covered by the
  67 +ordinary GNU General Public License. This license, the GNU Lesser
  68 +General Public License, applies to certain designated libraries, and
  69 +is quite different from the ordinary General Public License. We use
  70 +this license for certain libraries in order to permit linking those
  71 +libraries into non-free programs.
  72 +
  73 + When a program is linked with a library, whether statically or using
  74 +a shared library, the combination of the two is legally speaking a
  75 +combined work, a derivative of the original library. The ordinary
  76 +General Public License therefore permits such linking only if the
  77 +entire combination fits its criteria of freedom. The Lesser General
  78 +Public License permits more lax criteria for linking other code with
  79 +the library.
  80 +
  81 + We call this license the "Lesser" General Public License because it
  82 +does Less to protect the user's freedom than the ordinary General
  83 +Public License. It also provides other free software developers Less
  84 +of an advantage over competing non-free programs. These disadvantages
  85 +are the reason we use the ordinary General Public License for many
  86 +libraries. However, the Lesser license provides advantages in certain
  87 +special circumstances.
  88 +
  89 + For example, on rare occasions, there may be a special need to
  90 +encourage the widest possible use of a certain library, so that it becomes
  91 +a de-facto standard. To achieve this, non-free programs must be
  92 +allowed to use the library. A more frequent case is that a free
  93 +library does the same job as widely used non-free libraries. In this
  94 +case, there is little to gain by limiting the free library to free
  95 +software only, so we use the Lesser General Public License.
  96 +
  97 + In other cases, permission to use a particular library in non-free
  98 +programs enables a greater number of people to use a large body of
  99 +free software. For example, permission to use the GNU C Library in
  100 +non-free programs enables many more people to use the whole GNU
  101 +operating system, as well as its variant, the GNU/Linux operating
  102 +system.
  103 +
  104 + Although the Lesser General Public License is Less protective of the
  105 +users' freedom, it does ensure that the user of a program that is
  106 +linked with the Library has the freedom and the wherewithal to run
  107 +that program using a modified version of the Library.
  108 +
  109 + The precise terms and conditions for copying, distribution and
  110 +modification follow. Pay close attention to the difference between a
  111 +"work based on the library" and a "work that uses the library". The
  112 +former contains code derived from the library, whereas the latter must
  113 +be combined with the library in order to run.
  114 +
  115 + GNU LESSER GENERAL PUBLIC LICENSE
  116 + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  117 +
  118 + 0. This License Agreement applies to any software library or other
  119 +program which contains a notice placed by the copyright holder or
  120 +other authorized party saying it may be distributed under the terms of
  121 +this Lesser General Public License (also called "this License").
  122 +Each licensee is addressed as "you".
  123 +
  124 + A "library" means a collection of software functions and/or data
  125 +prepared so as to be conveniently linked with application programs
  126 +(which use some of those functions and data) to form executables.
  127 +
  128 + The "Library", below, refers to any such software library or work
  129 +which has been distributed under these terms. A "work based on the
  130 +Library" means either the Library or any derivative work under
  131 +copyright law: that is to say, a work containing the Library or a
  132 +portion of it, either verbatim or with modifications and/or translated
  133 +straightforwardly into another language. (Hereinafter, translation is
  134 +included without limitation in the term "modification".)
  135 +
  136 + "Source code" for a work means the preferred form of the work for
  137 +making modifications to it. For a library, complete source code means
  138 +all the source code for all modules it contains, plus any associated
  139 +interface definition files, plus the scripts used to control compilation
  140 +and installation of the library.
  141 +
  142 + Activities other than copying, distribution and modification are not
  143 +covered by this License; they are outside its scope. The act of
  144 +running a program using the Library is not restricted, and output from
  145 +such a program is covered only if its contents constitute a work based
  146 +on the Library (independent of the use of the Library in a tool for
  147 +writing it). Whether that is true depends on what the Library does
  148 +and what the program that uses the Library does.
  149 +
  150 + 1. You may copy and distribute verbatim copies of the Library's
  151 +complete source code as you receive it, in any medium, provided that
  152 +you conspicuously and appropriately publish on each copy an
  153 +appropriate copyright notice and disclaimer of warranty; keep intact
  154 +all the notices that refer to this License and to the absence of any
  155 +warranty; and distribute a copy of this License along with the
  156 +Library.
  157 +
  158 + You may charge a fee for the physical act of transferring a copy,
  159 +and you may at your option offer warranty protection in exchange for a
  160 +fee.
  161 +
  162 + 2. You may modify your copy or copies of the Library or any portion
  163 +of it, thus forming a work based on the Library, and copy and
  164 +distribute such modifications or work under the terms of Section 1
  165 +above, provided that you also meet all of these conditions:
  166 +
  167 + a) The modified work must itself be a software library.
  168 +
  169 + b) You must cause the files modified to carry prominent notices
  170 + stating that you changed the files and the date of any change.
  171 +
  172 + c) You must cause the whole of the work to be licensed at no
  173 + charge to all third parties under the terms of this License.
  174 +
  175 + d) If a facility in the modified Library refers to a function or a
  176 + table of data to be supplied by an application program that uses
  177 + the facility, other than as an argument passed when the facility
  178 + is invoked, then you must make a good faith effort to ensure that,
  179 + in the event an application does not supply such function or
  180 + table, the facility still operates, and performs whatever part of
  181 + its purpose remains meaningful.
  182 +
  183 + (For example, a function in a library to compute square roots has
  184 + a purpose that is entirely well-defined independent of the
  185 + application. Therefore, Subsection 2d requires that any
  186 + application-supplied function or table used by this function must
  187 + be optional: if the application does not supply it, the square
  188 + root function must still compute square roots.)
  189 +
  190 +These requirements apply to the modified work as a whole. If
  191 +identifiable sections of that work are not derived from the Library,
  192 +and can be reasonably considered independent and separate works in
  193 +themselves, then this License, and its terms, do not apply to those
  194 +sections when you distribute them as separate works. But when you
  195 +distribute the same sections as part of a whole which is a work based
  196 +on the Library, the distribution of the whole must be on the terms of
  197 +this License, whose permissions for other licensees extend to the
  198 +entire whole, and thus to each and every part regardless of who wrote
  199 +it.
  200 +
  201 +Thus, it is not the intent of this section to claim rights or contest
  202 +your rights to work written entirely by you; rather, the intent is to
  203 +exercise the right to control the distribution of derivative or
  204 +collective works based on the Library.
  205 +
  206 +In addition, mere aggregation of another work not based on the Library
  207 +with the Library (or with a work based on the Library) on a volume of
  208 +a storage or distribution medium does not bring the other work under
  209 +the scope of this License.
  210 +
  211 + 3. You may opt to apply the terms of the ordinary GNU General Public
  212 +License instead of this License to a given copy of the Library. To do
  213 +this, you must alter all the notices that refer to this License, so
  214 +that they refer to the ordinary GNU General Public License, version 2,
  215 +instead of to this License. (If a newer version than version 2 of the
  216 +ordinary GNU General Public License has appeared, then you can specify
  217 +that version instead if you wish.) Do not make any other change in
  218 +these notices.
  219 +
  220 + Once this change is made in a given copy, it is irreversible for
  221 +that copy, so the ordinary GNU General Public License applies to all
  222 +subsequent copies and derivative works made from that copy.
  223 +
  224 + This option is useful when you wish to copy part of the code of
  225 +the Library into a program that is not a library.
  226 +
  227 + 4. You may copy and distribute the Library (or a portion or
  228 +derivative of it, under Section 2) in object code or executable form
  229 +under the terms of Sections 1 and 2 above provided that you accompany
  230 +it with the complete corresponding machine-readable source code, which
  231 +must be distributed under the terms of Sections 1 and 2 above on a
  232 +medium customarily used for software interchange.
  233 +
  234 + If distribution of object code is made by offering access to copy
  235 +from a designated place, then offering equivalent access to copy the
  236 +source code from the same place satisfies the requirement to
  237 +distribute the source code, even though third parties are not
  238 +compelled to copy the source along with the object code.
  239 +
  240 + 5. A program that contains no derivative of any portion of the
  241 +Library, but is designed to work with the Library by being compiled or
  242 +linked with it, is called a "work that uses the Library". Such a
  243 +work, in isolation, is not a derivative work of the Library, and
  244 +therefore falls outside the scope of this License.
  245 +
  246 + However, linking a "work that uses the Library" with the Library
  247 +creates an executable that is a derivative of the Library (because it
  248 +contains portions of the Library), rather than a "work that uses the
  249 +library". The executable is therefore covered by this License.
  250 +Section 6 states terms for distribution of such executables.
  251 +
  252 + When a "work that uses the Library" uses material from a header file
  253 +that is part of the Library, the object code for the work may be a
  254 +derivative work of the Library even though the source code is not.
  255 +Whether this is true is especially significant if the work can be
  256 +linked without the Library, or if the work is itself a library. The
  257 +threshold for this to be true is not precisely defined by law.
  258 +
  259 + If such an object file uses only numerical parameters, data
  260 +structure layouts and accessors, and small macros and small inline
  261 +functions (ten lines or less in length), then the use of the object
  262 +file is unrestricted, regardless of whether it is legally a derivative
  263 +work. (Executables containing this object code plus portions of the
  264 +Library will still fall under Section 6.)
  265 +
  266 + Otherwise, if the work is a derivative of the Library, you may
  267 +distribute the object code for the work under the terms of Section 6.
  268 +Any executables containing that work also fall under Section 6,
  269 +whether or not they are linked directly with the Library itself.
  270 +
  271 + 6. As an exception to the Sections above, you may also combine or
  272 +link a "work that uses the Library" with the Library to produce a
  273 +work containing portions of the Library, and distribute that work
  274 +under terms of your choice, provided that the terms permit
  275 +modification of the work for the customer's own use and reverse
  276 +engineering for debugging such modifications.
  277 +
  278 + You must give prominent notice with each copy of the work that the
  279 +Library is used in it and that the Library and its use are covered by
  280 +this License. You must supply a copy of this License. If the work
  281 +during execution displays copyright notices, you must include the
  282 +copyright notice for the Library among them, as well as a reference
  283 +directing the user to the copy of this License. Also, you must do one
  284 +of these things:
  285 +
  286 + a) Accompany the work with the complete corresponding
  287 + machine-readable source code for the Library including whatever
  288 + changes were used in the work (which must be distributed under
  289 + Sections 1 and 2 above); and, if the work is an executable linked
  290 + with the Library, with the complete machine-readable "work that
  291 + uses the Library", as object code and/or source code, so that the
  292 + user can modify the Library and then relink to produce a modified
  293 + executable containing the modified Library. (It is understood
  294 + that the user who changes the contents of definitions files in the
  295 + Library will not necessarily be able to recompile the application
  296 + to use the modified definitions.)
  297 +
  298 + b) Use a suitable shared library mechanism for linking with the
  299 + Library. A suitable mechanism is one that (1) uses at run time a
  300 + copy of the library already present on the user's computer system,
  301 + rather than copying library functions into the executable, and (2)
  302 + will operate properly with a modified version of the library, if
  303 + the user installs one, as long as the modified version is
  304 + interface-compatible with the version that the work was made with.
  305 +
  306 + c) Accompany the work with a written offer, valid for at
  307 + least three years, to give the same user the materials
  308 + specified in Subsection 6a, above, for a charge no more
  309 + than the cost of performing this distribution.
  310 +
  311 + d) If distribution of the work is made by offering access to copy
  312 + from a designated place, offer equivalent access to copy the above
  313 + specified materials from the same place.
  314 +
  315 + e) verify that the user has already received a copy of these
  316 + materials or that you have already sent this user a copy.
  317 +
  318 + For an executable, the required form of the "work that uses the
  319 +Library" must include any data and utility programs needed for
  320 +reproducing the executable from it. However, as a special exception,
  321 +the materials to be distributed need not include anything that is
  322 +normally distributed (in either source or binary form) with the major
  323 +components (compiler, kernel, and so on) of the operating system on
  324 +which the executable runs, unless that component itself accompanies
  325 +the executable.
  326 +
  327 + It may happen that this requirement contradicts the license
  328 +restrictions of other proprietary libraries that do not normally
  329 +accompany the operating system. Such a contradiction means you cannot
  330 +use both them and the Library together in an executable that you
  331 +distribute.
  332 +
  333 + 7. You may place library facilities that are a work based on the
  334 +Library side-by-side in a single library together with other library
  335 +facilities not covered by this License, and distribute such a combined
  336 +library, provided that the separate distribution of the work based on
  337 +the Library and of the other library facilities is otherwise
  338 +permitted, and provided that you do these two things:
  339 +
  340 + a) Accompany the combined library with a copy of the same work
  341 + based on the Library, uncombined with any other library
  342 + facilities. This must be distributed under the terms of the
  343 + Sections above.
  344 +
  345 + b) Give prominent notice with the combined library of the fact
  346 + that part of it is a work based on the Library, and explaining
  347 + where to find the accompanying uncombined form of the same work.
  348 +
  349 + 8. You may not copy, modify, sublicense, link with, or distribute
  350 +the Library except as expressly provided under this License. Any
  351 +attempt otherwise to copy, modify, sublicense, link with, or
  352 +distribute the Library is void, and will automatically terminate your
  353 +rights under this License. However, parties who have received copies,
  354 +or rights, from you under this License will not have their licenses
  355 +terminated so long as such parties remain in full compliance.
  356 +
  357 + 9. You are not required to accept this License, since you have not
  358 +signed it. However, nothing else grants you permission to modify or
  359 +distribute the Library or its derivative works. These actions are
  360 +prohibited by law if you do not accept this License. Therefore, by
  361 +modifying or distributing the Library (or any work based on the
  362 +Library), you indicate your acceptance of this License to do so, and
  363 +all its terms and conditions for copying, distributing or modifying
  364 +the Library or works based on it.
  365 +
  366 + 10. Each time you redistribute the Library (or any work based on the
  367 +Library), the recipient automatically receives a license from the
  368 +original licensor to copy, distribute, link with or modify the Library
  369 +subject to these terms and conditions. You may not impose any further
  370 +restrictions on the recipients' exercise of the rights granted herein.
  371 +You are not responsible for enforcing compliance by third parties with
  372 +this License.
  373 +
  374 + 11. If, as a consequence of a court judgment or allegation of patent
  375 +infringement or for any other reason (not limited to patent issues),
  376 +conditions are imposed on you (whether by court order, agreement or
  377 +otherwise) that contradict the conditions of this License, they do not
  378 +excuse you from the conditions of this License. If you cannot
  379 +distribute so as to satisfy simultaneously your obligations under this
  380 +License and any other pertinent obligations, then as a consequence you
  381 +may not distribute the Library at all. For example, if a patent
  382 +license would not permit royalty-free redistribution of the Library by
  383 +all those who receive copies directly or indirectly through you, then
  384 +the only way you could satisfy both it and this License would be to
  385 +refrain entirely from distribution of the Library.
  386 +
  387 +If any portion of this section is held invalid or unenforceable under any
  388 +particular circumstance, the balance of the section is intended to apply,
  389 +and the section as a whole is intended to apply in other circumstances.
  390 +
  391 +It is not the purpose of this section to induce you to infringe any
  392 +patents or other property right claims or to contest validity of any
  393 +such claims; this section has the sole purpose of protecting the
  394 +integrity of the free software distribution system which is
  395 +implemented by public license practices. Many people have made
  396 +generous contributions to the wide range of software distributed
  397 +through that system in reliance on consistent application of that
  398 +system; it is up to the author/donor to decide if he or she is willing
  399 +to distribute software through any other system and a licensee cannot
  400 +impose that choice.
  401 +
  402 +This section is intended to make thoroughly clear what is believed to
  403 +be a consequence of the rest of this License.
  404 +
  405 + 12. If the distribution and/or use of the Library is restricted in
  406 +certain countries either by patents or by copyrighted interfaces, the
  407 +original copyright holder who places the Library under this License may add
  408 +an explicit geographical distribution limitation excluding those countries,
  409 +so that distribution is permitted only in or among countries not thus
  410 +excluded. In such case, this License incorporates the limitation as if
  411 +written in the body of this License.
  412 +
  413 + 13. The Free Software Foundation may publish revised and/or new
  414 +versions of the Lesser General Public License from time to time.
  415 +Such new versions will be similar in spirit to the present version,
  416 +but may differ in detail to address new problems or concerns.
  417 +
  418 +Each version is given a distinguishing version number. If the Library
  419 +specifies a version number of this License which applies to it and
  420 +"any later version", you have the option of following the terms and
  421 +conditions either of that version or of any later version published by
  422 +the Free Software Foundation. If the Library does not specify a
  423 +license version number, you may choose any version ever published by
  424 +the Free Software Foundation.
  425 +
  426 + 14. If you wish to incorporate parts of the Library into other free
  427 +programs whose distribution conditions are incompatible with these,
  428 +write to the author to ask for permission. For software which is
  429 +copyrighted by the Free Software Foundation, write to the Free
  430 +Software Foundation; we sometimes make exceptions for this. Our
  431 +decision will be guided by the two goals of preserving the free status
  432 +of all derivatives of our free software and of promoting the sharing
  433 +and reuse of software generally.
  434 +
  435 + NO WARRANTY
  436 +
  437 + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
  438 +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
  439 +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
  440 +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
  441 +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
  442 +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  443 +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
  444 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
  445 +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  446 +
  447 + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  448 +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
  449 +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
  450 +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
  451 +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
  452 +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
  453 +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
  454 +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
  455 +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  456 +DAMAGES.
  457 +
  458 + END OF TERMS AND CONDITIONS
  459 +
  460 + How to Apply These Terms to Your New Libraries
  461 +
  462 + If you develop a new library, and you want it to be of the greatest
  463 +possible use to the public, we recommend making it free software that
  464 +everyone can redistribute and change. You can do so by permitting
  465 +redistribution under these terms (or, alternatively, under the terms of the
  466 +ordinary General Public License).
  467 +
  468 + To apply these terms, attach the following notices to the library. It is
  469 +safest to attach them to the start of each source file to most effectively
  470 +convey the exclusion of warranty; and each file should have at least the
  471 +"copyright" line and a pointer to where the full notice is found.
  472 +
  473 + <one line to give the library's name and a brief idea of what it does.>
  474 + Copyright (C) <year> <name of author>
  475 +
  476 + This library is free software; you can redistribute it and/or
  477 + modify it under the terms of the GNU Lesser General Public
  478 + License as published by the Free Software Foundation; either
  479 + version 2.1 of the License, or (at your option) any later version.
  480 +
  481 + This library is distributed in the hope that it will be useful,
  482 + but WITHOUT ANY WARRANTY; without even the implied warranty of
  483 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  484 + Lesser General Public License for more details.
  485 +
  486 + You should have received a copy of the GNU Lesser General Public
  487 + License along with this library; if not, write to the Free Software
  488 + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  489 +
  490 +Also add information on how to contact you by electronic and paper mail.
  491 +
  492 +You should also get your employer (if you work as a programmer) or your
  493 +school, if any, to sign a "copyright disclaimer" for the library, if
  494 +necessary. Here is a sample; alter the names:
  495 +
  496 + Yoyodyne, Inc., hereby disclaims all copyright interest in the
  497 + library `Frob' (a library for tweaking knobs) written by James Random Hacker.
  498 +
  499 + <signature of Ty Coon>, 1 April 1990
  500 + Ty Coon, President of Vice
  501 +
  502 +That's all there is to it!
  503 +
  504 +
... ...
  1 +<?php
  2 +/**
  3 + * PHPMailer SPL autoloader.
  4 + * PHP Version 5
  5 + * @package PHPMailer
  6 + * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  7 + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  8 + * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  9 + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10 + * @author Brent R. Matzelle (original founder)
  11 + * @copyright 2012 - 2014 Marcus Bointon
  12 + * @copyright 2010 - 2012 Jim Jagielski
  13 + * @copyright 2004 - 2009 Andy Prevost
  14 + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15 + * @note This program is distributed in the hope that it will be useful - WITHOUT
  16 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17 + * FITNESS FOR A PARTICULAR PURPOSE.
  18 + */
  19 +
  20 +/**
  21 + * PHPMailer SPL autoloader.
  22 + * @param string $classname The name of the class to load
  23 + */
  24 +function PHPMailerAutoload($classname)
  25 +{
  26 + //Can't use __DIR__ as it's only in PHP 5.3+
  27 + $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
  28 + if (is_readable($filename)) {
  29 + require $filename;
  30 + }
  31 +}
  32 +
  33 +if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
  34 + //SPL autoloading was introduced in PHP 5.1.2
  35 + if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
  36 + spl_autoload_register('PHPMailerAutoload', true, true);
  37 + } else {
  38 + spl_autoload_register('PHPMailerAutoload');
  39 + }
  40 +} else {
  41 + /**
  42 + * Fall back to traditional autoload for old PHP versions
  43 + * @param string $classname The name of the class to load
  44 + */
  45 + function __autoload($classname)
  46 + {
  47 + PHPMailerAutoload($classname);
  48 + }
  49 +}
... ...
  1 +![PHPMailer](https://raw.github.com/PHPMailer/PHPMailer/master/examples/images/phpmailer.png)
  2 +
  3 +# PHPMailer - A full-featured email creation and transfer class for PHP
  4 +
  5 +Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.svg)](https://travis-ci.org/PHPMailer/PHPMailer)
  6 +[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/PHPMailer/PHPMailer/badges/quality-score.png?s=3758e21d279becdf847a557a56a3ed16dfec9d5d)](https://scrutinizer-ci.com/g/PHPMailer/PHPMailer/)
  7 +[![Code Coverage](https://scrutinizer-ci.com/g/PHPMailer/PHPMailer/badges/coverage.png?s=3fe6ca5fe8cd2cdf96285756e42932f7ca256962)](https://scrutinizer-ci.com/g/PHPMailer/PHPMailer/)
  8 +
  9 +## Class Features
  10 +
  11 +- Probably the world's most popular code for sending email from PHP!
  12 +- Used by many open-source projects: Drupal, SugarCRM, Yii, Joomla! and many more
  13 +- Integrated SMTP support - send without a local mail server
  14 +- Send emails with multiple TOs, CCs, BCCs and REPLY-TOs
  15 +- Multipart/alternative emails for mail clients that do not read HTML email
  16 +- Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
  17 +- SMTP authentication with LOGIN, PLAIN, NTLM and CRAM-MD5 mechanisms over SSL and TLS transports
  18 +- Native language support
  19 +- DKIM and S/MIME signing support
  20 +- Compatible with PHP 5.0 and later
  21 +- Much more!
  22 +
  23 +## Why you might need it
  24 +
  25 +Many PHP developers utilize email in their code. The only PHP function that supports this is the mail() function. However, it does not provide any assistance for making use of popular features such as HTML-based emails and attachments.
  26 +
  27 +Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules - the vast majority of code that you'll find online that uses the mail() function directly is just plain wrong!
  28 +*Please* don't be tempted to do it yourself - if you don't use PHPMailer, there are many other excellent libraries that you should look at before rolling your own - try SwiftMailer, Zend_Mail, eZcomponents etc.
  29 +
  30 +The PHP mail() function usually sends via a local mail server, typically fronted by a `sendmail` binary on Linux, BSD and OS X platforms, however, Windows usually doesn't include a local mail server; PHPMailer's integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
  31 +
  32 +## License
  33 +
  34 +This software is licenced under the [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html). Please read LICENSE for information on the
  35 +software availability and distribution.
  36 +
  37 +## Installation & loading
  38 +
  39 +PHPMailer is available via [Composer/Packagist](https://packagist.org/packages/phpmailer/phpmailer). Alternatively, just copy the contents of the PHPMailer folder into somewhere that's in your PHP `include_path` setting. If you don't speak git or just want a tarball, click the 'zip' button at the top of the page in GitHub.
  40 +
  41 +PHPMailer provides an SPL-compatible autoloader, and that is the preferred way of loading the library - just `require '/path/to/PHPMailerAutoload.php';` and everything should work. The autoloader does not throw errors if it can't find classes so it prepends itself to the SPL list, allowing your own (or your framework's) autoloader to catch errors. SPL autoloading was introduced in PHP 5.1.0, so if you are using a version older than that you will need to require/include each class manually.
  42 +PHPMailer does *not* declare a namespace because namespaces were only introduced in PHP 5.3.
  43 +
  44 +### Minimal installation
  45 +
  46 +While installing the entire package manually or with composer is simple, convenient and reliable, you may want to include only vital files in your project. At the very least you will need [class.phpmailer.php](class.phpmailer.php). If you're using SMTP, you'll need [class.smtp.php](class.smtp.php), and if you're using POP-before SMTP, you'll need [class.pop3.php](class.pop3.php). For all of these, we recommend you use [the autoloader](PHPMailerAutoload.php) too. You can skip the [language](language/) folder if you're not showing errors to users and can make do with English-only errors. You may need the additional classes in the [extras](extras/) folder if you are using those features, including NTLM authentication, advanced HTML-to-text conversion and ics generation.
  47 +
  48 +## A Simple Example
  49 +
  50 +```php
  51 +<?php
  52 +require 'PHPMailerAutoload.php';
  53 +
  54 +$mail = new PHPMailer;
  55 +
  56 +$mail->isSMTP(); // Set mailer to use SMTP
  57 +$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
  58 +$mail->SMTPAuth = true; // Enable SMTP authentication
  59 +$mail->Username = 'user@example.com'; // SMTP username
  60 +$mail->Password = 'secret'; // SMTP password
  61 +$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
  62 +
  63 +$mail->From = 'from@example.com';
  64 +$mail->FromName = 'Mailer';
  65 +$mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient
  66 +$mail->addAddress('ellen@example.com'); // Name is optional
  67 +$mail->addReplyTo('info@example.com', 'Information');
  68 +$mail->addCC('cc@example.com');
  69 +$mail->addBCC('bcc@example.com');
  70 +
  71 +$mail->WordWrap = 50; // Set word wrap to 50 characters
  72 +$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
  73 +$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
  74 +$mail->isHTML(true); // Set email format to HTML
  75 +
  76 +$mail->Subject = 'Here is the subject';
  77 +$mail->Body = 'This is the HTML message body <b>in bold!</b>';
  78 +$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
  79 +
  80 +if(!$mail->send()) {
  81 + echo 'Message could not be sent.';
  82 + echo 'Mailer Error: ' . $mail->ErrorInfo;
  83 +} else {
  84 + echo 'Message has been sent';
  85 +}
  86 +```
  87 +
  88 +You'll find plenty more to play with in the [examples](examples/) folder.
  89 +
  90 +That's it. You should now be ready to use PHPMailer!
  91 +
  92 +## Localization
  93 +PHPMailer defaults to English, but in the [language](language/) folder you'll find numerous (39 at the time of writing) translations for PHPMailer error messages that you may encounter. Their filenames contain [ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1) language code for the translations, for example `fr` for French. To specify a language, you need to tell PHPMailer which one to use, like this:
  94 +
  95 +```php
  96 +// To load the French version
  97 +$mail->setLanguage('fr', '/optional/path/to/language/directory/');
  98 +```
  99 +
  100 +We welcome corrections and new languages - if you're looking for corrections to do, run the [phpmailerLangTest.php](test/phpmailerLangTest.php) script in the tests folder and it will show any missing translations.
  101 +
  102 +## Documentation
  103 +
  104 +Generated documentation is [available online](http://phpmailer.github.io/PHPMailer/).
  105 +
  106 +You'll find some basic user-level docs in the [docs](docs/) folder, and you can generate complete API-level documentation using the [generatedocs.sh](docs/generatedocs.sh) shell script in the docs folder, though you'll need to install [PHPDocumentor](http://www.phpdoc.org) first. You may find [the unit tests](test/phpmailerTest.php) a good source of how to do various operations such as encryption.
  107 +
  108 +## Tests
  109 +
  110 +There is a PHPUnit test script in the [test](test/) folder.
  111 +
  112 +Build status: [![Build Status](https://travis-ci.org/PHPMailer/PHPMailer.svg)](https://travis-ci.org/PHPMailer/PHPMailer)
  113 +
  114 +If this isn't passing, is there something you can do to help?
  115 +
  116 +## Contributing
  117 +
  118 +Please submit bug reports, suggestions and pull requests to the [GitHub issue tracker](https://github.com/PHPMailer/PHPMailer/issues).
  119 +
  120 +We're particularly interested in fixing edge-cases, expanding test coverage and updating translations.
  121 +
  122 +With the move to the PHPMailer GitHub organisation, you'll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone:
  123 +
  124 +`git remote set-url upstream https://github.com/PHPMailer/PHPMailer.git`
  125 +
  126 +Please *don't* use the SourceForge or Google Code projects any more.
  127 +
  128 +## Changelog
  129 +
  130 +See [changelog](changelog.md).
  131 +
  132 +## History
  133 +- PHPMailer was originally written in 2001 by Brent R. Matzelle as a [SourceForge project](http://sourceforge.net/projects/phpmailer/).
  134 +- Marcus Bointon (coolbru on SF) and Andy Prevost (codeworxtech) took over the project in 2004.
  135 +- Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski.
  136 +- Marcus created his fork on [GitHub](https://github.com/Synchro/PHPMailer).
  137 +- Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer.
  138 +- PHPMailer moves to the [PHPMailer organisation](https://github.com/PHPMailer) on GitHub.
  139 +
  140 +### What's changed since moving from SourceForge?
  141 +- Official successor to the SourceForge and Google Code projects.
  142 +- Test suite.
  143 +- Continuous integration with Travis-CI.
  144 +- Composer support.
  145 +- Public development.
  146 +- Additional languages and language strings.
  147 +- CRAM-MD5 authentication support.
  148 +- Preserves full repo history of authors, commits and branches from the original SourceForge project.
... ...
  1 +# ChangeLog
  2 +
  3 +## Version 5.2.8 (May 14th 2014)
  4 +* Increase timeout to match RFC2821 section 4.5.3.2 and thus not fail greetdelays, fixes #104
  5 +* Add timestamps to default debug output
  6 +* Add connection events and new level 3 to debug output options
  7 +* Chinese language update (Thanks to @binaryoung)
  8 +* Allow custom Mailer types (Thanks to @michield)
  9 +* Cope with spaces around SMTP host specs
  10 +* Fix processing of multiple hosts in connect string
  11 +* Added Galician translation (Thanks to @donatorouco)
  12 +* Autoloader now prepends
  13 +* Docs updates
  14 +* Add Latvian translation (Thanks to @eddsstudio)
  15 +* Add Belarusian translation (Thanks to @amaksymiuk)
  16 +* Make autoloader work better on older PHP versions
  17 +* Avoid double-encoding if mbstring is overloading mail()
  18 +* Add Portuguese translation (Thanks to @Jonadabe)
  19 +* Make quoted-printable encoder respect line ending setting
  20 +* Improve Chinese translation (Thanks to @PeterDaveHello)
  21 +* Add Georgian translation (Thanks to @akalongman)
  22 +* Add Greek translation (Thanks to @lenasterg)
  23 +* Fix serverHostname on PHP < 5.3
  24 +* Improve performance of SMTP class
  25 +* Implement automatic 7bit downgrade
  26 +* Add Vietnamese translation (Thanks to @vinades)
  27 +* Improve example images, switch to PNG
  28 +* Add Croatian translation (Thanks to @hrvoj3e)
  29 +* Remove setting the Return-Path and deprecate the Return-path property - it's just wrong!
  30 +* Fix language file loading if CWD has changed (@stephandesouza)
  31 +* Add HTML5 email validation pattern
  32 +* Improve Turkish translations (Thanks to @yasinaydin)
  33 +* Improve Romanian translations (Thanks to @aflorea)
  34 +* Fix quoted-printable encoding of multiparts
  35 +* Check php.ini for path to sendmail/qmail before using default
  36 +* Improve Farsi translation (Thanks to @MHM5000)
  37 +* Don't use quoted-printable encoding for multipart types
  38 +* Add Serbian translation (Thanks to ajevremovic at gmail.com)
  39 +* Remove useless PHP5 check
  40 +* Use SVG for build status badges
  41 +* Store MessageDate on creation
  42 +* Better default behaviour for validateAddress
  43 +
  44 +## Version 5.2.7 (September 12th 2013)
  45 +* Add Ukranian translation from @Krezalis
  46 +* Support for do_verp
  47 +* Fix bug in CRAM-MD5 AUTH
  48 +* Propagate Debugoutput option to SMTP class (@Reblutus)
  49 +* Determine MIME type of attachments automatically
  50 +* Add cross-platform, multibyte-safe pathinfo replacement (with tests) and use it
  51 +* Add a new 'html' Debugoutput type
  52 +* Clean up SMTP debug output, remove embedded HTML
  53 +* Some small changes in header formatting to improve IETF msglint test results
  54 +* Update test_script to use some recently changed features, rename to code_generator
  55 +* Generated code actually works!
  56 +* Update SyntaxHighlighter
  57 +* Major overhaul and cleanup of example code
  58 +* New PHPMailer graphic
  59 +* msgHTML now uses RFC2392-compliant content ids
  60 +* Add line break normalization function and use it in msgHTML
  61 +* Don't set unnecessary reply-to addresses
  62 +* Make fakesendmail.sh a bit cleaner and safer
  63 +* Set a content-transfer-encoding on multiparts (fixes msglint error)
  64 +* Fix cid generation in msgHTML (Thanks to @digitalthought)
  65 +* Fix handling of multiple SMTP servers (Thanks to @NanoCaiordo)
  66 +* SMTP->connect() now supports stream context options (Thanks to @stanislavdavid)
  67 +* Add support for iCal event alternatives (Thanks to @reblutus)
  68 +* Update to Polish language file (Thanks to Krzysztof Kowalewski)
  69 +* Update to Norwegian language file (Thanks to @datagutten)
  70 +* Update to Hungarian language file (Thanks to @dominicus-75)
  71 +* Add Persian/Farsi translation from @jaii
  72 +* Make SMTPDebug property type match type in SMTP class
  73 +* Add unit tests for DKIM
  74 +* Major refactor of SMTP class
  75 +* Reformat to PSR-2 coding standard
  76 +* Introduce autoloader
  77 +* Allow overriding of SMTP class
  78 +* Overhaul of PHPDocs
  79 +* Fix broken Q-encoding
  80 +* Czech language update (Thanks to @nemelu)
  81 +* Removal of excess blank lines in messages
  82 +* Added fake POP server and unit tests for POP-before-SMTP
  83 +
  84 +## Version 5.2.6 (April 11th 2013)
  85 +* Reflect move to PHPMailer GitHub organisation at https://github.com/PHPMailer/PHPMailer
  86 +* Fix unbumped version numbers
  87 +* Update packagist.org with new location
  88 +* Clean up Changelog
  89 +
  90 +## Version 5.2.5 (April 6th 2013)
  91 +* First official release after move from Google Code
  92 +* Fixes for qmail when sending via mail()
  93 +* Merge in changes from Google code 5.2.4 release
  94 +* Minor coding standards cleanup in SMTP class
  95 +* Improved unit tests, now tests S/MIME signing
  96 +* Travis-CI support on GitHub, runs tests with fake SMTP server
  97 +
  98 +## Version 5.2.4 (February 19, 2013)
  99 +* Fix tag and version bug.
  100 +* un-deprecate isSMTP(), isMail(), IsSendmail() and isQmail().
  101 +* Numerous translation updates
  102 +
  103 +## Version 5.2.3 (February 8, 2013)
  104 +* Fix issue with older PCREs and ValidateAddress() (Bugz: 124)
  105 +* Add CRAM-MD5 authentication, thanks to Elijah madden, https://github.com/okonomiyaki3000
  106 +* Replacement of obsolete Quoted-Printable encoder with a much better implementation
  107 +* Composer package definition
  108 +* New language added: Hebrew
  109 +
  110 +## Version 5.2.2 (December 3, 2012)
  111 +* Some fixes and syncs from https://github.com/Synchro/PHPMailer
  112 +* Add Slovak translation, thanks to Michal Tinka
  113 +
  114 +## Version 5.2.2-rc2 (November 6, 2012)
  115 +* Fix SMTP server rotation (Bugz: 118)
  116 +* Allow override of autogen'ed 'Date' header (for Drupal's
  117 + og_mailinglist module)
  118 +* No whitespace after '-f' option (Bugz: 116)
  119 +* Work around potential warning (Bugz: 114)
  120 +
  121 +## Version 5.2.2-rc1 (September 28, 2012)
  122 +* Header encoding works with long lines (Bugz: 93)
  123 +* Turkish language update (Bugz: 94)
  124 +* undefined $pattern in EncodeQ bug squashed (Bugz: 98)
  125 +* use of mail() in safe_mode now works (Bugz: 96)
  126 +* ValidateAddress() now 'public static' so people can override the
  127 + default and use their own validation scheme.
  128 +* ValidateAddress() no longer uses broken FILTER_VALIDATE_EMAIL
  129 +* Added in AUTH PLAIN SMTP authentication
  130 +
  131 +## Version 5.2.2-beta2 (August 17, 2012)
  132 +* Fixed Postfix VERP support (Bugz: 92)
  133 +* Allow action_function callbacks to pass/use
  134 + the From address (passed as final param)
  135 +* Prevent inf look for get_lines() (Bugz: 77)
  136 +* New public var ($UseSendmailOptions). Only pass sendmail()
  137 + options iff we really are using sendmail or something sendmail
  138 + compatible. (Bugz: 75)
  139 +* default setting for LE returned to "\n" due to popular demand.
  140 +
  141 +## Version 5.2.2-beta1 (July 13, 2012)
  142 +* Expose PreSend() and PostSend() as public methods to allow
  143 + for more control if serializing message sending.
  144 +* GetSentMIMEMessage() only constructs the message copy when
  145 + needed. Save memory.
  146 +* Only pass params to mail() if the underlying MTA is
  147 + "sendmail" (as defined as "having the string sendmail
  148 + in its pathname") [#69]
  149 +* Attachments now work with Amazon SES and others [Bugz#70]
  150 +* Debug output now sent to stdout (via echo) or error_log [Bugz#5]
  151 +* New var: Debugoutput (for above) [Bugz#5]
  152 +* SMTP reads now Timeout aware (new var: Timeout=15) [Bugz#71]
  153 +* SMTP reads now can have a Timelimit associated with them
  154 + (new var: Timelimit=30)[Bugz#71]
  155 +* Fix quoting issue associated with charsets
  156 +* default setting for LE is now RFC compliant: "\r\n"
  157 +* Return-Path can now be user defined (new var: ReturnPath)
  158 + (the default is "" which implies no change from previous
  159 + behavior, which was to use either From or Sender) [Bugz#46]
  160 +* X-Mailer header can now be disabled (by setting to a
  161 + whitespace string, eg " ") [Bugz#66]
  162 +* Bugz closed: #68, #60, #42, #43, #59, #55, #66, #48, #49,
  163 + #52, #31, #41, #5. #70, #69
  164 +
  165 +## Version 5.2.1 (January 16, 2012)
  166 +* Closed several bugs #5
  167 +* Performance improvements
  168 +* MsgHTML() now returns the message as required.
  169 +* New method: GetSentMIMEMessage() (returns full copy of sent message)
  170 +
  171 +## Version 5.2 (July 19, 2011)
  172 +* protected MIME body and header
  173 +* better DKIM DNS Resource Record support
  174 +* better aly handling
  175 +* htmlfilter class added to extras
  176 +* moved to Apache Extras
  177 +
  178 +## Version 5.1 (October 20, 2009)
  179 +* fixed filename issue with AddStringAttachment (thanks to Tony)
  180 +* fixed "SingleTo" property, now works with Senmail, Qmail, and SMTP in
  181 + addition to PHP mail()
  182 +* added DKIM digital signing functionality, new properties:
  183 + - DKIM_domain (sets the domain name)
  184 + - DKIM_private (holds DKIM private key)
  185 + - DKIM_passphrase (holds your DKIM passphrase)
  186 + - DKIM_selector (holds the DKIM "selector")
  187 + - DKIM_identity (holds the identifying email address)
  188 +* added callback function support
  189 + - callback function parameters include:
  190 + result, to, cc, bcc, subject and body
  191 + - see the test/test_callback.php file for usage.
  192 +* added "auto" identity functionality
  193 + - can automatically add:
  194 + - Return-path (if Sender not set)
  195 + - Reply-To (if ReplyTo not set)
  196 + - can be disabled:
  197 + - $mail->SetFrom('yourname@yourdomain.com','First Last',false);
  198 + - or by adding the $mail->Sender and/or $mail->ReplyTo properties
  199 +
  200 +Note: "auto" identity added to help with emails ending up in spam or junk boxes because of missing headers
  201 +
  202 +## Version 5.0.2 (May 24, 2009)
  203 +* Fix for missing attachments when inline graphics are present
  204 +* Fix for missing Cc in header when using SMTP (mail was sent,
  205 + but not displayed in header -- Cc receiver only saw email To:
  206 + line and no Cc line, but did get the email (To receiver
  207 + saw same)
  208 +
  209 +## Version 5.0.1 (April 05, 2009)
  210 +* Temporary fix for missing attachments
  211 +
  212 +## Version 5.0.0 (April 02, 2009)
  213 +With the release of this version, we are initiating a new version numbering
  214 +system to differentiate from the PHP4 version of PHPMailer.
  215 +Most notable in this release is fully object oriented code.
  216 +
  217 +### class.smtp.php:
  218 +* Refactored class.smtp.php to support new exception handling
  219 +* code size reduced from 29.2 Kb to 25.6 Kb
  220 +* Removed unnecessary functions from class.smtp.php:
  221 + - public function Expand($name) {
  222 + - public function Help($keyword="") {
  223 + - public function Noop() {
  224 + - public function Send($from) {
  225 + - public function SendOrMail($from) {
  226 + - public function Verify($name) {
  227 +
  228 +### class.phpmailer.php:
  229 +* Refactored class.phpmailer.php with new exception handling
  230 +* Changed processing functionality of Sendmail and Qmail so they cannot be
  231 + inadvertently used
  232 +* removed getFile() function, just became a simple wrapper for
  233 + file_get_contents()
  234 +* added check for PHP version (will gracefully exit if not at least PHP 5.0)
  235 +* enhanced code to check if an attachment source is the same as an embedded or
  236 + inline graphic source to eliminate duplicate attachments
  237 +
  238 +### New /test_script
  239 +We have written a test script you can use to test the script as part of your
  240 +installation. Once you press submit, the test script will send a multi-mime
  241 +email with either the message you type in or an HTML email with an inline
  242 +graphic. Two attachments are included in the email (one of the attachments
  243 +is also the inline graphic so you can see that only one copy of the graphic
  244 +is sent in the email). The test script will also display the functional
  245 +script that you can copy/paste to your editor to duplicate the functionality.
  246 +
  247 +### New examples
  248 +All new examples in both basic and advanced modes. Advanced examples show
  249 + Exception handling.
  250 +
  251 +### PHPDocumentator (phpdocs) documentation for PHPMailer version 5.0.0
  252 +All new documentation
  253 +
  254 +## Version 2.3 (November 06, 2008)
  255 +* added Arabic language (many thanks to Bahjat Al Mostafa)
  256 +* removed English language from language files and made it a default within
  257 + class.phpmailer.php - if no language is found, it will default to use
  258 + the english language translation
  259 +* fixed public/private declarations
  260 +* corrected line 1728, $basedir to $directory
  261 +* added $sign_cert_file to avoid improper duplicate use of $sign_key_file
  262 +* corrected $this->Hello on line 612 to $this->Helo
  263 +* changed default of $LE to "\r\n" to comply with RFC 2822. Can be set by the user
  264 + if default is not acceptable
  265 +* removed trim() from return results in EncodeQP
  266 +* /test and three files it contained are removed from version 2.3
  267 +* fixed phpunit.php for compliance with PHP5
  268 +* changed $this->AltBody = $textMsg; to $this->AltBody = html_entity_decode($textMsg);
  269 +* We have removed the /phpdoc from the downloads. All documentation is now on
  270 + the http://phpmailer.codeworxtech.com website.
  271 +
  272 +## Version 2.2.1 () July 19 2008
  273 +* fixed line 1092 in class.smtp.php (my apologies, error on my part)
  274 +
  275 +## Version 2.2 () July 15 2008
  276 +* Fixed redirect issue (display of UTF-8 in thank you redirect)
  277 +* fixed error in getResponse function declaration (class.pop3.php)
  278 +* PHPMailer now PHP6 compliant
  279 +* fixed line 1092 in class.smtp.php (endless loop from missing = sign)
  280 +
  281 +## Version 2.1 (Wed, June 04 2008)
  282 +NOTE: WE HAVE A NEW LANGUAGE VARIABLE FOR DIGITALLY SIGNED S/MIME EMAILS. IF YOU CAN HELP WITH LANGUAGES OTHER THAN ENGLISH AND SPANISH, IT WOULD BE APPRECIATED.
  283 +
  284 +* added S/MIME functionality (ability to digitally sign emails)
  285 + BIG THANKS TO "sergiocambra" for posting this patch back in November 2007.
  286 + The "Signed Emails" functionality adds the Sign method to pass the private key
  287 + filename and the password to read it, and then email will be sent with
  288 + content-type multipart/signed and with the digital signature attached.
  289 +* fully compatible with E_STRICT error level
  290 + - Please note:
  291 + In about half the test environments this development version was subjected
  292 + to, an error was thrown for the date() functions used (line 1565 and 1569).
  293 + This is NOT a PHPMailer error, it is the result of an incorrectly configured
  294 + PHP5 installation. The fix is to modify your 'php.ini' file and include the
  295 + date.timezone = Etc/UTC (or your own zone)
  296 + directive, to your own server timezone
  297 + - If you do get this error, and are unable to access your php.ini file:
  298 + In your PHP script, add
  299 + `date_default_timezone_set('Etc/UTC');`
  300 + - do not try to use
  301 + `$myVar = date_default_timezone_get();`
  302 + as a test, it will throw an error.
  303 +* added ability to define path (mainly for embedded images)
  304 + function `MsgHTML($message,$basedir='')` ... where:
  305 + `$basedir` is the fully qualified path
  306 +* fixed `MsgHTML()` function:
  307 + - Embedded Images where images are specified by `<protocol>://` will not be altered or embedded
  308 +* fixed the return value of SMTP exit code ( pclose )
  309 +* addressed issue of multibyte characters in subject line and truncating
  310 +* added ability to have user specified Message ID
  311 + (default is still that PHPMailer create a unique Message ID)
  312 +* corrected unidentified message type to 'application/octet-stream'
  313 +* fixed chunk_split() multibyte issue (thanks to Colin Brown, et al).
  314 +* added check for added attachments
  315 +* enhanced conversion of HTML to text in MsgHTML (thanks to "brunny")
  316 +
  317 +## Version 2.1.0beta2 (Sun, Dec 02 2007)
  318 +* implemented updated EncodeQP (thanks to coolbru, aka Marcus Bointon)
  319 +* finished all testing, all known bugs corrected, enhancements tested
  320 +
  321 +Note: will NOT work with PHP4.
  322 +
  323 +Please note, this is BETA software **DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS; INTENDED STRICTLY FOR TESTING**
  324 +
  325 +## Version 2.1.0beta1
  326 +Please note, this is BETA software
  327 +** DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS
  328 + INTENDED STRICTLY FOR TESTING
  329 +
  330 +## Version 2.0.0 rc2 (Fri, Nov 16 2007), interim release
  331 +* implements new property to control VERP in class.smtp.php
  332 + example (requires instantiating class.smtp.php):
  333 + $mail->do_verp = true;
  334 +* POP-before-SMTP functionality included, thanks to Richard Davey
  335 + (see class.pop3.php & pop3_before_smtp_test.php for examples)
  336 +* included example showing how to use PHPMailer with GMAIL
  337 +* fixed the missing Cc in SendMail() and Mail()
  338 +
  339 +## Version 2.0.0 rc1 (Thu, Nov 08 2007), interim release
  340 +* dramatically simplified using inline graphics ... it's fully automated and requires no user input
  341 +* added automatic document type detection for attachments and pictures
  342 +* added MsgHTML() function to replace Body tag for HTML emails
  343 +* fixed the SendMail security issues (input validation vulnerability)
  344 +* enhanced the AddAddresses functionality so that the "Name" portion is used in the email address
  345 +* removed the need to use the AltBody method (set from the HTML, or default text used)
  346 +* set the PHP Mail() function as the default (still support SendMail, SMTP Mail)
  347 +* removed the need to set the IsHTML property (set automatically)
  348 +* added Estonian language file by Indrek P&auml;ri
  349 +* added header injection patch
  350 +* added "set" method to permit users to create their own pseudo-properties like 'X-Headers', etc.
  351 +* fixed warning message in SMTP get_lines method
  352 +* added TLS/SSL SMTP support.
  353 +* PHPMailer has been tested with PHP4 (4.4.7) and PHP5 (5.2.7)
  354 +* Works with PHP installed as a module or as CGI-PHP
  355 +NOTE: will NOT work with PHP5 in E_STRICT error mode
  356 +
  357 +## Version 1.73 (Sun, Jun 10 2005)
  358 +* Fixed denial of service bug: http://www.cybsec.com/vuln/PHPMailer-DOS.pdf
  359 +* Now has a total of 20 translations
  360 +* Fixed alt attachments bug: http://tinyurl.com/98u9k
  361 +
  362 +## Version 1.72 (Wed, May 25 2004)
  363 +* Added Dutch, Swedish, Czech, Norwegian, and Turkish translations.
  364 +* Received: Removed this method because spam filter programs like
  365 + SpamAssassin reject this header.
  366 +* Fixed error count bug.
  367 +* SetLanguage default is now "language/".
  368 +* Fixed magic_quotes_runtime bug.
  369 +
  370 +## Version 1.71 (Tue, Jul 28 2003)
  371 +* Made several speed enhancements
  372 +* Added German and Italian translation files
  373 +* Fixed HELO/AUTH bugs on keep-alive connects
  374 +* Now provides an error message if language file does not load
  375 +* Fixed attachment EOL bug
  376 +* Updated some unclear documentation
  377 +* Added additional tests and improved others
  378 +
  379 +## Version 1.70 (Mon, Jun 20 2003)
  380 +* Added SMTP keep-alive support
  381 +* Added IsError method for error detection
  382 +* Added error message translation support (SetLanguage)
  383 +* Refactored many methods to increase library performance
  384 +* Hello now sends the newer EHLO message before HELO as per RFC 2821
  385 +* Removed the boundary class and replaced it with GetBoundary
  386 +* Removed queue support methods
  387 +* New $Hostname variable
  388 +* New Message-ID header
  389 +* Received header reformat
  390 +* Helo variable default changed to $Hostname
  391 +* Removed extra spaces in Content-Type definition (#667182)
  392 +* Return-Path should be set to Sender when set
  393 +* Adds Q or B encoding to headers when necessary
  394 +* quoted-encoding should now encode NULs \000
  395 +* Fixed encoding of body/AltBody (#553370)
  396 +* Adds "To: undisclosed-recipients:;" when all recipients are hidden (BCC)
  397 +* Multiple bug fixes
  398 +
  399 +## Version 1.65 (Fri, Aug 09 2002)
  400 +* Fixed non-visible attachment bug (#585097) for Outlook
  401 +* SMTP connections are now closed after each transaction
  402 +* Fixed SMTP::Expand return value
  403 +* Converted SMTP class documentation to phpDocumentor format
  404 +
  405 +## Version 1.62 (Wed, Jun 26 2002)
  406 +* Fixed multi-attach bug
  407 +* Set proper word wrapping
  408 +* Reduced memory use with attachments
  409 +* Added more debugging
  410 +* Changed documentation to phpDocumentor format
  411 +
  412 +## Version 1.60 (Sat, Mar 30 2002)
  413 +* Sendmail pipe and address patch (Christian Holtje)
  414 +* Added embedded image and read confirmation support (A. Ognio)
  415 +* Added unit tests
  416 +* Added SMTP timeout support (*nix only)
  417 +* Added possibly temporary PluginDir variable for SMTP class
  418 +* Added LE message line ending variable
  419 +* Refactored boundary and attachment code
  420 +* Eliminated SMTP class warnings
  421 +* Added SendToQueue method for future queuing support
  422 +
  423 +## Version 1.54 (Wed, Dec 19 2001)
  424 +* Add some queuing support code
  425 +* Fixed a pesky multi/alt bug
  426 +* Messages are no longer forced to have "To" addresses
  427 +
  428 +## Version 1.50 (Thu, Nov 08 2001)
  429 +* Fix extra lines when not using SMTP mailer
  430 +* Set WordWrap variable to int with a zero default
  431 +
  432 +## Version 1.47 (Tue, Oct 16 2001)
  433 +* Fixed Received header code format
  434 +* Fixed AltBody order error
  435 +* Fixed alternate port warning
  436 +
  437 +## Version 1.45 (Tue, Sep 25 2001)
  438 +* Added enhanced SMTP debug support
  439 +* Added support for multiple ports on SMTP
  440 +* Added Received header for tracing
  441 +* Fixed AddStringAttachment encoding
  442 +* Fixed possible header name quote bug
  443 +* Fixed wordwrap() trim bug
  444 +* Couple other small bug fixes
  445 +
  446 +## Version 1.41 (Wed, Aug 22 2001)
  447 +* Fixed AltBody bug w/o attachments
  448 +* Fixed rfc_date() for certain mail servers
  449 +
  450 +## Version 1.40 (Sun, Aug 12 2001)
  451 +* Added multipart/alternative support (AltBody)
  452 +* Documentation update
  453 +* Fixed bug in Mercury MTA
  454 +
  455 +## Version 1.29 (Fri, Aug 03 2001)
  456 +* Added AddStringAttachment() method
  457 +* Added SMTP authentication support
  458 +
  459 +## Version 1.28 (Mon, Jul 30 2001)
  460 +* Fixed a typo in SMTP class
  461 +* Fixed header issue with Imail (win32) SMTP server
  462 +* Made fopen() calls for attachments use "rb" to fix win32 error
  463 +
  464 +## Version 1.25 (Mon, Jul 02 2001)
  465 +* Added RFC 822 date fix (Patrice)
  466 +* Added improved error handling by adding a $ErrorInfo variable
  467 +* Removed MailerDebug variable (obsolete with new error handler)
  468 +
  469 +## Version 1.20 (Mon, Jun 25 2001)
  470 +* Added quoted-printable encoding (Patrice)
  471 +* Set Version as public and removed PrintVersion()
  472 +* Changed phpdoc to only display public variables and methods
  473 +
  474 +## Version 1.19 (Thu, Jun 21 2001)
  475 +* Fixed MS Mail header bug
  476 +* Added fix for Bcc problem with mail(). *Does not work on Win32*
  477 + (See PHP bug report: http://www.php.net/bugs.php?id=11616)
  478 +* mail() no longer passes a fifth parameter when not needed
  479 +
  480 +## Version 1.15 (Fri, Jun 15 2001)
  481 +Note: these changes contributed by Patrice Fournier
  482 +* Changed all remaining \n to \r\n
  483 +* Bcc: header no longer writen to message except
  484 + when sent directly to sendmail
  485 +* Added a small message to non-MIME compliant mail reader
  486 +* Added Sender variable to change the Sender email
  487 + used in -f for sendmail/mail and in 'MAIL FROM' for smtp mode
  488 +* Changed boundary setting to a place it will be set only once
  489 +* Removed transfer encoding for whole message when using multipart
  490 +* Message body now uses Encoding in multipart messages
  491 +* Can set encoding and type to attachments 7bit, 8bit
  492 + and binary attachment are sent as is, base64 are encoded
  493 +* Can set Encoding to base64 to send 8 bits body
  494 + through 7 bits servers
  495 +
  496 +## Version 1.10 (Tue, Jun 12 2001)
  497 +* Fixed win32 mail header bug (printed out headers in message body)
  498 +
  499 +## Version 1.09 (Fri, Jun 08 2001)
  500 +* Changed date header to work with Netscape mail programs
  501 +* Altered phpdoc documentation
  502 +
  503 +## Version 1.08 (Tue, Jun 05 2001)
  504 +* Added enhanced error-checking
  505 +* Added phpdoc documentation to source
  506 +
  507 +## Version 1.06 (Fri, Jun 01 2001)
  508 +* Added optional name for file attachments
  509 +
  510 +## Version 1.05 (Tue, May 29 2001)
  511 +* Code cleanup
  512 +* Eliminated sendmail header warning message
  513 +* Fixed possible SMTP error
  514 +
  515 +## Version 1.03 (Thu, May 24 2001)
  516 +* Fixed problem where qmail sends out duplicate messages
  517 +
  518 +## Version 1.02 (Wed, May 23 2001)
  519 +* Added multiple recipient and attachment Clear* methods
  520 +* Added Sendmail public variable
  521 +* Fixed problem with loading SMTP library multiple times
  522 +
  523 +## Version 0.98 (Tue, May 22 2001)
  524 +* Fixed problem with redundant mail hosts sending out multiple messages
  525 +* Added additional error handler code
  526 +* Added AddCustomHeader() function
  527 +* Added support for Microsoft mail client headers (affects priority)
  528 +* Fixed small bug with Mailer variable
  529 +* Added PrintVersion() function
  530 +
  531 +## Version 0.92 (Tue, May 15 2001)
  532 +* Changed file names to class.phpmailer.php and class.smtp.php to match
  533 + current PHP class trend.
  534 +* Fixed problem where body not being printed when a message is attached
  535 +* Several small bug fixes
  536 +
  537 +## Version 0.90 (Tue, April 17 2001)
  538 +* Initial public release
... ...
This diff could not be displayed because it is too large.
  1 +<?php
  2 +/**
  3 + * PHPMailer POP-Before-SMTP Authentication Class.
  4 + * PHP Version 5
  5 + * @package PHPMailer
  6 + * @link https://github.com/PHPMailer/PHPMailer/
  7 + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  8 + * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  9 + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10 + * @author Brent R. Matzelle (original founder)
  11 + * @copyright 2012 - 2014 Marcus Bointon
  12 + * @copyright 2010 - 2012 Jim Jagielski
  13 + * @copyright 2004 - 2009 Andy Prevost
  14 + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15 + * @note This program is distributed in the hope that it will be useful - WITHOUT
  16 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17 + * FITNESS FOR A PARTICULAR PURPOSE.
  18 + */
  19 +
  20 +/**
  21 + * PHPMailer POP-Before-SMTP Authentication Class.
  22 + * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication.
  23 + * Does not support APOP.
  24 + * @package PHPMailer
  25 + * @author Richard Davey (original author) <rich@corephp.co.uk>
  26 + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  27 + * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  28 + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  29 + */
  30 +class POP3
  31 +{
  32 + /**
  33 + * The POP3 PHPMailer Version number.
  34 + * @type string
  35 + * @access public
  36 + */
  37 + public $Version = '5.2.8';
  38 +
  39 + /**
  40 + * Default POP3 port number.
  41 + * @type int
  42 + * @access public
  43 + */
  44 + public $POP3_PORT = 110;
  45 +
  46 + /**
  47 + * Default timeout in seconds.
  48 + * @type int
  49 + * @access public
  50 + */
  51 + public $POP3_TIMEOUT = 30;
  52 +
  53 + /**
  54 + * POP3 Carriage Return + Line Feed.
  55 + * @type string
  56 + * @access public
  57 + * @deprecated Use the constant instead
  58 + */
  59 + public $CRLF = "\r\n";
  60 +
  61 + /**
  62 + * Debug display level.
  63 + * Options: 0 = no, 1+ = yes
  64 + * @type int
  65 + * @access public
  66 + */
  67 + public $do_debug = 0;
  68 +
  69 + /**
  70 + * POP3 mail server hostname.
  71 + * @type string
  72 + * @access public
  73 + */
  74 + public $host;
  75 +
  76 + /**
  77 + * POP3 port number.
  78 + * @type int
  79 + * @access public
  80 + */
  81 + public $port;
  82 +
  83 + /**
  84 + * POP3 Timeout Value in seconds.
  85 + * @type int
  86 + * @access public
  87 + */
  88 + public $tval;
  89 +
  90 + /**
  91 + * POP3 username
  92 + * @type string
  93 + * @access public
  94 + */
  95 + public $username;
  96 +
  97 + /**
  98 + * POP3 password.
  99 + * @type string
  100 + * @access public
  101 + */
  102 + public $password;
  103 +
  104 + /**
  105 + * Resource handle for the POP3 connection socket.
  106 + * @type resource
  107 + * @access private
  108 + */
  109 + private $pop_conn;
  110 +
  111 + /**
  112 + * Are we connected?
  113 + * @type bool
  114 + * @access private
  115 + */
  116 + private $connected;
  117 +
  118 + /**
  119 + * Error container.
  120 + * @type array
  121 + * @access private
  122 + */
  123 + private $error;
  124 +
  125 + /**
  126 + * Line break constant
  127 + */
  128 + const CRLF = "\r\n";
  129 +
  130 + /**
  131 + * Constructor.
  132 + * @access public
  133 + */
  134 + public function __construct()
  135 + {
  136 + $this->pop_conn = 0;
  137 + $this->connected = false;
  138 + $this->error = null;
  139 + }
  140 +
  141 + /**
  142 + * Simple static wrapper for all-in-one POP before SMTP
  143 + * @param $host
  144 + * @param bool $port
  145 + * @param bool $tval
  146 + * @param string $username
  147 + * @param string $password
  148 + * @param int $debug_level
  149 + * @return bool
  150 + */
  151 + public static function popBeforeSmtp(
  152 + $host,
  153 + $port = false,
  154 + $tval = false,
  155 + $username = '',
  156 + $password = '',
  157 + $debug_level = 0
  158 + ) {
  159 + $pop = new POP3;
  160 + return $pop->authorise($host, $port, $tval, $username, $password, $debug_level);
  161 + }
  162 +
  163 + /**
  164 + * Authenticate with a POP3 server.
  165 + * A connect, login, disconnect sequence
  166 + * appropriate for POP-before SMTP authorisation.
  167 + * @access public
  168 + * @param string $host
  169 + * @param bool|int $port
  170 + * @param bool|int $tval
  171 + * @param string $username
  172 + * @param string $password
  173 + * @param int $debug_level
  174 + * @return bool
  175 + */
  176 + public function authorise($host, $port = false, $tval = false, $username = '', $password = '', $debug_level = 0)
  177 + {
  178 + $this->host = $host;
  179 + // If no port value provided, use default
  180 + if ($port === false) {
  181 + $this->port = $this->POP3_PORT;
  182 + } else {
  183 + $this->port = $port;
  184 + }
  185 + // If no timeout value provided, use default
  186 + if ($tval === false) {
  187 + $this->tval = $this->POP3_TIMEOUT;
  188 + } else {
  189 + $this->tval = $tval;
  190 + }
  191 + $this->do_debug = $debug_level;
  192 + $this->username = $username;
  193 + $this->password = $password;
  194 + // Refresh the error log
  195 + $this->error = null;
  196 + // connect
  197 + $result = $this->connect($this->host, $this->port, $this->tval);
  198 + if ($result) {
  199 + $login_result = $this->login($this->username, $this->password);
  200 + if ($login_result) {
  201 + $this->disconnect();
  202 + return true;
  203 + }
  204 + }
  205 + // We need to disconnect regardless of whether the login succeeded
  206 + $this->disconnect();
  207 + return false;
  208 + }
  209 +
  210 + /**
  211 + * Connect to a POP3 server.
  212 + * @access public
  213 + * @param string $host
  214 + * @param bool|int $port
  215 + * @param integer $tval
  216 + * @return boolean
  217 + */
  218 + public function connect($host, $port = false, $tval = 30)
  219 + {
  220 + // Are we already connected?
  221 + if ($this->connected) {
  222 + return true;
  223 + }
  224 +
  225 + //On Windows this will raise a PHP Warning error if the hostname doesn't exist.
  226 + //Rather than suppress it with @fsockopen, capture it cleanly instead
  227 + set_error_handler(array($this, 'catchWarning'));
  228 +
  229 + // connect to the POP3 server
  230 + $this->pop_conn = fsockopen(
  231 + $host, // POP3 Host
  232 + $port, // Port #
  233 + $errno, // Error Number
  234 + $errstr, // Error Message
  235 + $tval
  236 + ); // Timeout (seconds)
  237 + // Restore the error handler
  238 + restore_error_handler();
  239 + // Does the Error Log now contain anything?
  240 + if ($this->error && $this->do_debug >= 1) {
  241 + $this->displayErrors();
  242 + }
  243 + // Did we connect?
  244 + if ($this->pop_conn == false) {
  245 + // It would appear not...
  246 + $this->error = array(
  247 + 'error' => "Failed to connect to server $host on port $port",
  248 + 'errno' => $errno,
  249 + 'errstr' => $errstr
  250 + );
  251 + if ($this->do_debug >= 1) {
  252 + $this->displayErrors();
  253 + }
  254 + return false;
  255 + }
  256 +
  257 + // Increase the stream time-out
  258 + // Check for PHP 4.3.0 or later
  259 + if (version_compare(phpversion(), '5.0.0', 'ge')) {
  260 + stream_set_timeout($this->pop_conn, $tval, 0);
  261 + } else {
  262 + // Does not work on Windows
  263 + if (substr(PHP_OS, 0, 3) !== 'WIN') {
  264 + socket_set_timeout($this->pop_conn, $tval, 0);
  265 + }
  266 + }
  267 +
  268 + // Get the POP3 server response
  269 + $pop3_response = $this->getResponse();
  270 + // Check for the +OK
  271 + if ($this->checkResponse($pop3_response)) {
  272 + // The connection is established and the POP3 server is talking
  273 + $this->connected = true;
  274 + return true;
  275 + }
  276 + return false;
  277 + }
  278 +
  279 + /**
  280 + * Log in to the POP3 server.
  281 + * Does not support APOP (RFC 2828, 4949).
  282 + * @access public
  283 + * @param string $username
  284 + * @param string $password
  285 + * @return boolean
  286 + */
  287 + public function login($username = '', $password = '')
  288 + {
  289 + if ($this->connected == false) {
  290 + $this->error = 'Not connected to POP3 server';
  291 +
  292 + if ($this->do_debug >= 1) {
  293 + $this->displayErrors();
  294 + }
  295 + }
  296 + if (empty($username)) {
  297 + $username = $this->username;
  298 + }
  299 + if (empty($password)) {
  300 + $password = $this->password;
  301 + }
  302 +
  303 + // Send the Username
  304 + $this->sendString("USER $username" . self::CRLF);
  305 + $pop3_response = $this->getResponse();
  306 + if ($this->checkResponse($pop3_response)) {
  307 + // Send the Password
  308 + $this->sendString("PASS $password" . self::CRLF);
  309 + $pop3_response = $this->getResponse();
  310 + if ($this->checkResponse($pop3_response)) {
  311 + return true;
  312 + }
  313 + }
  314 + return false;
  315 + }
  316 +
  317 + /**
  318 + * Disconnect from the POP3 server.
  319 + * @access public
  320 + */
  321 + public function disconnect()
  322 + {
  323 + $this->sendString('QUIT');
  324 + //The QUIT command may cause the daemon to exit, which will kill our connection
  325 + //So ignore errors here
  326 + @fclose($this->pop_conn);
  327 + }
  328 +
  329 + /**
  330 + * Get a response from the POP3 server.
  331 + * $size is the maximum number of bytes to retrieve
  332 + * @param integer $size
  333 + * @return string
  334 + * @access private
  335 + */
  336 + private function getResponse($size = 128)
  337 + {
  338 + $response = fgets($this->pop_conn, $size);
  339 + if ($this->do_debug >= 1) {
  340 + echo "Server -> Client: $response";
  341 + }
  342 + return $response;
  343 + }
  344 +
  345 + /**
  346 + * Send raw data to the POP3 server.
  347 + * @param string $string
  348 + * @return integer
  349 + * @access private
  350 + */
  351 + private function sendString($string)
  352 + {
  353 + if ($this->pop_conn) {
  354 + if ($this->do_debug >= 2) { //Show client messages when debug >= 2
  355 + echo "Client -> Server: $string";
  356 + }
  357 + return fwrite($this->pop_conn, $string, strlen($string));
  358 + }
  359 + return 0;
  360 + }
  361 +
  362 + /**
  363 + * Checks the POP3 server response.
  364 + * Looks for for +OK or -ERR.
  365 + * @param string $string
  366 + * @return boolean
  367 + * @access private
  368 + */
  369 + private function checkResponse($string)
  370 + {
  371 + if (substr($string, 0, 3) !== '+OK') {
  372 + $this->error = array(
  373 + 'error' => "Server reported an error: $string",
  374 + 'errno' => 0,
  375 + 'errstr' => ''
  376 + );
  377 + if ($this->do_debug >= 1) {
  378 + $this->displayErrors();
  379 + }
  380 + return false;
  381 + } else {
  382 + return true;
  383 + }
  384 + }
  385 +
  386 + /**
  387 + * Display errors if debug is enabled.
  388 + * @access private
  389 + */
  390 + private function displayErrors()
  391 + {
  392 + echo '<pre>';
  393 + foreach ($this->error as $single_error) {
  394 + print_r($single_error);
  395 + }
  396 + echo '</pre>';
  397 + }
  398 +
  399 + /**
  400 + * POP3 connection error handler.
  401 + * @param integer $errno
  402 + * @param string $errstr
  403 + * @param string $errfile
  404 + * @param integer $errline
  405 + * @access private
  406 + */
  407 + private function catchWarning($errno, $errstr, $errfile, $errline)
  408 + {
  409 + $this->error[] = array(
  410 + 'error' => "Connecting to the POP3 server raised a PHP warning: ",
  411 + 'errno' => $errno,
  412 + 'errstr' => $errstr,
  413 + 'errfile' => $errfile,
  414 + 'errline' => $errline
  415 + );
  416 + }
  417 +}
... ...
  1 +<?php
  2 +/**
  3 + * PHPMailer RFC821 SMTP email transport class.
  4 + * PHP Version 5
  5 + * @package PHPMailer
  6 + * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  7 + * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  8 + * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  9 + * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10 + * @author Brent R. Matzelle (original founder)
  11 + * @copyright 2014 Marcus Bointon
  12 + * @copyright 2010 - 2012 Jim Jagielski
  13 + * @copyright 2004 - 2009 Andy Prevost
  14 + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15 + * @note This program is distributed in the hope that it will be useful - WITHOUT
  16 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17 + * FITNESS FOR A PARTICULAR PURPOSE.
  18 + */
  19 +
  20 +/**
  21 + * PHPMailer RFC821 SMTP email transport class.
  22 + * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
  23 + * @package PHPMailer
  24 + * @author Chris Ryan <unknown@example.com>
  25 + * @author Marcus Bointon <phpmailer@synchromedia.co.uk>
  26 + */
  27 +class SMTP
  28 +{
  29 + /**
  30 + * The PHPMailer SMTP version number.
  31 + * @type string
  32 + */
  33 + const VERSION = '5.2.8';
  34 +
  35 + /**
  36 + * SMTP line break constant.
  37 + * @type string
  38 + */
  39 + const CRLF = "\r\n";
  40 +
  41 + /**
  42 + * The SMTP port to use if one is not specified.
  43 + * @type int
  44 + */
  45 + const DEFAULT_SMTP_PORT = 25;
  46 +
  47 + /**
  48 + * The maximum line length allowed by RFC 2822 section 2.1.1
  49 + * @type int
  50 + */
  51 + const MAX_LINE_LENGTH = 998;
  52 +
  53 + /**
  54 + * The PHPMailer SMTP Version number.
  55 + * @type string
  56 + * @deprecated Use the constant instead
  57 + * @see SMTP::VERSION
  58 + */
  59 + public $Version = '5.2.8';
  60 +
  61 + /**
  62 + * SMTP server port number.
  63 + * @type int
  64 + * @deprecated This is only ever used as a default value, so use the constant instead
  65 + * @see SMTP::DEFAULT_SMTP_PORT
  66 + */
  67 + public $SMTP_PORT = 25;
  68 +
  69 + /**
  70 + * SMTP reply line ending.
  71 + * @type string
  72 + * @deprecated Use the constant instead
  73 + * @see SMTP::CRLF
  74 + */
  75 + public $CRLF = "\r\n";
  76 +
  77 + /**
  78 + * Debug output level.
  79 + * Options:
  80 + * * `0` No output
  81 + * * `1` Commands
  82 + * * `2` Data and commands
  83 + * * `3` As 2 plus connection status
  84 + * * `4` Low-level data output
  85 + * @type int
  86 + */
  87 + public $do_debug = 0;
  88 +
  89 + /**
  90 + * How to handle debug output.
  91 + * Options:
  92 + * * `echo` Output plain-text as-is, appropriate for CLI
  93 + * * `html` Output escaped, line breaks converted to <br>, appropriate for browser output
  94 + * * `error_log` Output to error log as configured in php.ini
  95 + * @type string
  96 + */
  97 + public $Debugoutput = 'echo';
  98 +
  99 + /**
  100 + * Whether to use VERP.
  101 + * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  102 + * @link http://www.postfix.org/VERP_README.html Info on VERP
  103 + * @type bool
  104 + */
  105 + public $do_verp = false;
  106 +
  107 + /**
  108 + * The timeout value for connection, in seconds.
  109 + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  110 + * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
  111 + * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
  112 + * @type int
  113 + */
  114 + public $Timeout = 300;
  115 +
  116 + /**
  117 + * The SMTP timelimit value for reads, in seconds.
  118 + * @type int
  119 + */
  120 + public $Timelimit = 30;
  121 +
  122 + /**
  123 + * The socket for the server connection.
  124 + * @type resource
  125 + */
  126 + protected $smtp_conn;
  127 +
  128 + /**
  129 + * Error message, if any, for the last call.
  130 + * @type string
  131 + */
  132 + protected $error = '';
  133 +
  134 + /**
  135 + * The reply the server sent to us for HELO.
  136 + * @type string
  137 + */
  138 + protected $helo_rply = '';
  139 +
  140 + /**
  141 + * The most recent reply received from the server.
  142 + * @type string
  143 + */
  144 + protected $last_reply = '';
  145 +
  146 + /**
  147 + * Constructor.
  148 + * @access public
  149 + */
  150 + public function __construct()
  151 + {
  152 + $this->smtp_conn = 0;
  153 + $this->error = null;
  154 + $this->helo_rply = null;
  155 + $this->do_debug = 0;
  156 + }
  157 +
  158 + /**
  159 + * Output debugging info via a user-selected method.
  160 + * @param string $str Debug string to output
  161 + * @return void
  162 + */
  163 + protected function edebug($str)
  164 + {
  165 + switch ($this->Debugoutput) {
  166 + case 'error_log':
  167 + //Don't output, just log
  168 + error_log($str);
  169 + break;
  170 + case 'html':
  171 + //Cleans up output a bit for a better looking, HTML-safe output
  172 + echo htmlentities(
  173 + preg_replace('/[\r\n]+/', '', $str),
  174 + ENT_QUOTES,
  175 + 'UTF-8'
  176 + )
  177 + . "<br>\n";
  178 + break;
  179 + case 'echo':
  180 + default:
  181 + echo gmdate('Y-m-d H:i:s')."\t".trim($str)."\n";
  182 + }
  183 + }
  184 +
  185 + /**
  186 + * Connect to an SMTP server.
  187 + * @param string $host SMTP server IP or host name
  188 + * @param int $port The port number to connect to
  189 + * @param int $timeout How long to wait for the connection to open
  190 + * @param array $options An array of options for stream_context_create()
  191 + * @access public
  192 + * @return bool
  193 + */
  194 + public function connect($host, $port = null, $timeout = 30, $options = array())
  195 + {
  196 + // Clear errors to avoid confusion
  197 + $this->error = null;
  198 + // Make sure we are __not__ connected
  199 + if ($this->connected()) {
  200 + // Already connected, generate error
  201 + $this->error = array('error' => 'Already connected to a server');
  202 + return false;
  203 + }
  204 + if (empty($port)) {
  205 + $port = self::DEFAULT_SMTP_PORT;
  206 + }
  207 + // Connect to the SMTP server
  208 + if ($this->do_debug >= 3) {
  209 + $this->edebug('Connection: opening');
  210 + }
  211 + $errno = 0;
  212 + $errstr = '';
  213 + $socket_context = stream_context_create($options);
  214 + //Suppress errors; connection failures are handled at a higher level
  215 + $this->smtp_conn = @stream_socket_client(
  216 + $host . ":" . $port,
  217 + $errno,
  218 + $errstr,
  219 + $timeout,
  220 + STREAM_CLIENT_CONNECT,
  221 + $socket_context
  222 + );
  223 + // Verify we connected properly
  224 + if (empty($this->smtp_conn)) {
  225 + $this->error = array(
  226 + 'error' => 'Failed to connect to server',
  227 + 'errno' => $errno,
  228 + 'errstr' => $errstr
  229 + );
  230 + if ($this->do_debug >= 1) {
  231 + $this->edebug(
  232 + 'SMTP ERROR: ' . $this->error['error']
  233 + . ": $errstr ($errno)"
  234 + );
  235 + }
  236 + return false;
  237 + }
  238 + if ($this->do_debug >= 3) {
  239 + $this->edebug('Connection: opened');
  240 + }
  241 + // SMTP server can take longer to respond, give longer timeout for first read
  242 + // Windows does not have support for this timeout function
  243 + if (substr(PHP_OS, 0, 3) != 'WIN') {
  244 + $max = ini_get('max_execution_time');
  245 + if ($max != 0 && $timeout > $max) { // Don't bother if unlimited
  246 + @set_time_limit($timeout);
  247 + }
  248 + stream_set_timeout($this->smtp_conn, $timeout, 0);
  249 + }
  250 + // Get any announcement
  251 + $announce = $this->get_lines();
  252 + if ($this->do_debug >= 2) {
  253 + $this->edebug('SERVER -> CLIENT: ' . $announce);
  254 + }
  255 + return true;
  256 + }
  257 +
  258 + /**
  259 + * Initiate a TLS (encrypted) session.
  260 + * @access public
  261 + * @return bool
  262 + */
  263 + public function startTLS()
  264 + {
  265 + if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
  266 + return false;
  267 + }
  268 + // Begin encrypted connection
  269 + if (!stream_socket_enable_crypto(
  270 + $this->smtp_conn,
  271 + true,
  272 + STREAM_CRYPTO_METHOD_TLS_CLIENT
  273 + )) {
  274 + return false;
  275 + }
  276 + return true;
  277 + }
  278 +
  279 + /**
  280 + * Perform SMTP authentication.
  281 + * Must be run after hello().
  282 + * @see hello()
  283 + * @param string $username The user name
  284 + * @param string $password The password
  285 + * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5)
  286 + * @param string $realm The auth realm for NTLM
  287 + * @param string $workstation The auth workstation for NTLM
  288 + * @access public
  289 + * @return bool True if successfully authenticated.
  290 + */
  291 + public function authenticate(
  292 + $username,
  293 + $password,
  294 + $authtype = 'LOGIN',
  295 + $realm = '',
  296 + $workstation = ''
  297 + ) {
  298 + if (empty($authtype)) {
  299 + $authtype = 'LOGIN';
  300 + }
  301 + switch ($authtype) {
  302 + case 'PLAIN':
  303 + // Start authentication
  304 + if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
  305 + return false;
  306 + }
  307 + // Send encoded username and password
  308 + if (!$this->sendCommand(
  309 + 'User & Password',
  310 + base64_encode("\0" . $username . "\0" . $password),
  311 + 235
  312 + )
  313 + ) {
  314 + return false;
  315 + }
  316 + break;
  317 + case 'LOGIN':
  318 + // Start authentication
  319 + if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
  320 + return false;
  321 + }
  322 + if (!$this->sendCommand("Username", base64_encode($username), 334)) {
  323 + return false;
  324 + }
  325 + if (!$this->sendCommand("Password", base64_encode($password), 235)) {
  326 + return false;
  327 + }
  328 + break;
  329 + case 'NTLM':
  330 + /*
  331 + * ntlm_sasl_client.php
  332 + * Bundled with Permission
  333 + *
  334 + * How to telnet in windows:
  335 + * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
  336 + * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
  337 + */
  338 + require_once 'extras/ntlm_sasl_client.php';
  339 + $temp = new stdClass();
  340 + $ntlm_client = new ntlm_sasl_client_class;
  341 + //Check that functions are available
  342 + if (!$ntlm_client->Initialize($temp)) {
  343 + $this->error = array('error' => $temp->error);
  344 + if ($this->do_debug >= 1) {
  345 + $this->edebug(
  346 + 'You need to enable some modules in your php.ini file: '
  347 + . $this->error['error']
  348 + );
  349 + }
  350 + return false;
  351 + }
  352 + //msg1
  353 + $msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1
  354 +
  355 + if (!$this->sendCommand(
  356 + 'AUTH NTLM',
  357 + 'AUTH NTLM ' . base64_encode($msg1),
  358 + 334
  359 + )
  360 + ) {
  361 + return false;
  362 + }
  363 + //Though 0 based, there is a white space after the 3 digit number
  364 + //msg2
  365 + $challenge = substr($this->last_reply, 3);
  366 + $challenge = base64_decode($challenge);
  367 + $ntlm_res = $ntlm_client->NTLMResponse(
  368 + substr($challenge, 24, 8),
  369 + $password
  370 + );
  371 + //msg3
  372 + $msg3 = $ntlm_client->TypeMsg3(
  373 + $ntlm_res,
  374 + $username,
  375 + $realm,
  376 + $workstation
  377 + );
  378 + // send encoded username
  379 + return $this->sendCommand('Username', base64_encode($msg3), 235);
  380 + break;
  381 + case 'CRAM-MD5':
  382 + // Start authentication
  383 + if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
  384 + return false;
  385 + }
  386 + // Get the challenge
  387 + $challenge = base64_decode(substr($this->last_reply, 4));
  388 +
  389 + // Build the response
  390 + $response = $username . ' ' . $this->hmac($challenge, $password);
  391 +
  392 + // send encoded credentials
  393 + return $this->sendCommand('Username', base64_encode($response), 235);
  394 + break;
  395 + }
  396 + return true;
  397 + }
  398 +
  399 + /**
  400 + * Calculate an MD5 HMAC hash.
  401 + * Works like hash_hmac('md5', $data, $key)
  402 + * in case that function is not available
  403 + * @param string $data The data to hash
  404 + * @param string $key The key to hash with
  405 + * @access protected
  406 + * @return string
  407 + */
  408 + protected function hmac($data, $key)
  409 + {
  410 + if (function_exists('hash_hmac')) {
  411 + return hash_hmac('md5', $data, $key);
  412 + }
  413 +
  414 + // The following borrowed from
  415 + // http://php.net/manual/en/function.mhash.php#27225
  416 +
  417 + // RFC 2104 HMAC implementation for php.
  418 + // Creates an md5 HMAC.
  419 + // Eliminates the need to install mhash to compute a HMAC
  420 + // Hacked by Lance Rushing
  421 +
  422 + $bytelen = 64; // byte length for md5
  423 + if (strlen($key) > $bytelen) {
  424 + $key = pack('H*', md5($key));
  425 + }
  426 + $key = str_pad($key, $bytelen, chr(0x00));
  427 + $ipad = str_pad('', $bytelen, chr(0x36));
  428 + $opad = str_pad('', $bytelen, chr(0x5c));
  429 + $k_ipad = $key ^ $ipad;
  430 + $k_opad = $key ^ $opad;
  431 +
  432 + return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  433 + }
  434 +
  435 + /**
  436 + * Check connection state.
  437 + * @access public
  438 + * @return bool True if connected.
  439 + */
  440 + public function connected()
  441 + {
  442 + if (!empty($this->smtp_conn)) {
  443 + $sock_status = stream_get_meta_data($this->smtp_conn);
  444 + if ($sock_status['eof']) {
  445 + // the socket is valid but we are not connected
  446 + if ($this->do_debug >= 1) {
  447 + $this->edebug(
  448 + 'SMTP NOTICE: EOF caught while checking if connected'
  449 + );
  450 + }
  451 + $this->close();
  452 + return false;
  453 + }
  454 + return true; // everything looks good
  455 + }
  456 + return false;
  457 + }
  458 +
  459 + /**
  460 + * Close the socket and clean up the state of the class.
  461 + * Don't use this function without first trying to use QUIT.
  462 + * @see quit()
  463 + * @access public
  464 + * @return void
  465 + */
  466 + public function close()
  467 + {
  468 + $this->error = null; // so there is no confusion
  469 + $this->helo_rply = null;
  470 + if (!empty($this->smtp_conn)) {
  471 + // close the connection and cleanup
  472 + fclose($this->smtp_conn);
  473 + if ($this->do_debug >= 3) {
  474 + $this->edebug('Connection: closed');
  475 + }
  476 + $this->smtp_conn = 0;
  477 + }
  478 + }
  479 +
  480 + /**
  481 + * Send an SMTP DATA command.
  482 + * Issues a data command and sends the msg_data to the server,
  483 + * finializing the mail transaction. $msg_data is the message
  484 + * that is to be send with the headers. Each header needs to be
  485 + * on a single line followed by a <CRLF> with the message headers
  486 + * and the message body being separated by and additional <CRLF>.
  487 + * Implements rfc 821: DATA <CRLF>
  488 + * @param string $msg_data Message data to send
  489 + * @access public
  490 + * @return bool
  491 + */
  492 + public function data($msg_data)
  493 + {
  494 + if (!$this->sendCommand('DATA', 'DATA', 354)) {
  495 + return false;
  496 + }
  497 + /* The server is ready to accept data!
  498 + * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
  499 + * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
  500 + * smaller lines to fit within the limit.
  501 + * We will also look for lines that start with a '.' and prepend an additional '.'.
  502 + * NOTE: this does not count towards line-length limit.
  503 + */
  504 +
  505 + // Normalize line breaks before exploding
  506 + $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
  507 +
  508 + /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
  509 + * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
  510 + * process all lines before a blank line as headers.
  511 + */
  512 +
  513 + $field = substr($lines[0], 0, strpos($lines[0], ':'));
  514 + $in_headers = false;
  515 + if (!empty($field) && strpos($field, ' ') === false) {
  516 + $in_headers = true;
  517 + }
  518 +
  519 + foreach ($lines as $line) {
  520 + $lines_out = array();
  521 + if ($in_headers and $line == '') {
  522 + $in_headers = false;
  523 + }
  524 + // ok we need to break this line up into several smaller lines
  525 + //This is a small micro-optimisation: isset($str[$len]) is equivalent to (strlen($str) > $len)
  526 + while (isset($line[self::MAX_LINE_LENGTH])) {
  527 + //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
  528 + //so as to avoid breaking in the middle of a word
  529 + $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
  530 + if (!$pos) { //Deliberately matches both false and 0
  531 + //No nice break found, add a hard break
  532 + $pos = self::MAX_LINE_LENGTH - 1;
  533 + $lines_out[] = substr($line, 0, $pos);
  534 + $line = substr($line, $pos);
  535 + } else {
  536 + //Break at the found point
  537 + $lines_out[] = substr($line, 0, $pos);
  538 + //Move along by the amount we dealt with
  539 + $line = substr($line, $pos + 1);
  540 + }
  541 + /* If processing headers add a LWSP-char to the front of new line
  542 + * RFC822 section 3.1.1
  543 + */
  544 + if ($in_headers) {
  545 + $line = "\t" . $line;
  546 + }
  547 + }
  548 + $lines_out[] = $line;
  549 +
  550 + // Send the lines to the server
  551 + foreach ($lines_out as $line_out) {
  552 + //RFC2821 section 4.5.2
  553 + if (!empty($line_out) and $line_out[0] == '.') {
  554 + $line_out = '.' . $line_out;
  555 + }
  556 + $this->client_send($line_out . self::CRLF);
  557 + }
  558 + }
  559 +
  560 + // Message data has been sent, complete the command
  561 + return $this->sendCommand('DATA END', '.', 250);
  562 + }
  563 +
  564 + /**
  565 + * Send an SMTP HELO or EHLO command.
  566 + * Used to identify the sending server to the receiving server.
  567 + * This makes sure that client and server are in a known state.
  568 + * Implements RFC 821: HELO <SP> <domain> <CRLF>
  569 + * and RFC 2821 EHLO.
  570 + * @param string $host The host name or IP to connect to
  571 + * @access public
  572 + * @return bool
  573 + */
  574 + public function hello($host = '')
  575 + {
  576 + // Try extended hello first (RFC 2821)
  577 + return (bool)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
  578 + }
  579 +
  580 + /**
  581 + * Send an SMTP HELO or EHLO command.
  582 + * Low-level implementation used by hello()
  583 + * @see hello()
  584 + * @param string $hello The HELO string
  585 + * @param string $host The hostname to say we are
  586 + * @access protected
  587 + * @return bool
  588 + */
  589 + protected function sendHello($hello, $host)
  590 + {
  591 + $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
  592 + $this->helo_rply = $this->last_reply;
  593 + return $noerror;
  594 + }
  595 +
  596 + /**
  597 + * Send an SMTP MAIL command.
  598 + * Starts a mail transaction from the email address specified in
  599 + * $from. Returns true if successful or false otherwise. If True
  600 + * the mail transaction is started and then one or more recipient
  601 + * commands may be called followed by a data command.
  602 + * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
  603 + * @param string $from Source address of this message
  604 + * @access public
  605 + * @return bool
  606 + */
  607 + public function mail($from)
  608 + {
  609 + $useVerp = ($this->do_verp ? ' XVERP' : '');
  610 + return $this->sendCommand(
  611 + 'MAIL FROM',
  612 + 'MAIL FROM:<' . $from . '>' . $useVerp,
  613 + 250
  614 + );
  615 + }
  616 +
  617 + /**
  618 + * Send an SMTP QUIT command.
  619 + * Closes the socket if there is no error or the $close_on_error argument is true.
  620 + * Implements from rfc 821: QUIT <CRLF>
  621 + * @param bool $close_on_error Should the connection close if an error occurs?
  622 + * @access public
  623 + * @return bool
  624 + */
  625 + public function quit($close_on_error = true)
  626 + {
  627 + $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
  628 + $err = $this->error; //Save any error
  629 + if ($noerror or $close_on_error) {
  630 + $this->close();
  631 + $this->error = $err; //Restore any error from the quit command
  632 + }
  633 + return $noerror;
  634 + }
  635 +
  636 + /**
  637 + * Send an SMTP RCPT command.
  638 + * Sets the TO argument to $toaddr.
  639 + * Returns true if the recipient was accepted false if it was rejected.
  640 + * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
  641 + * @param string $toaddr The address the message is being sent to
  642 + * @access public
  643 + * @return bool
  644 + */
  645 + public function recipient($toaddr)
  646 + {
  647 + return $this->sendCommand(
  648 + 'RCPT TO',
  649 + 'RCPT TO:<' . $toaddr . '>',
  650 + array(250, 251)
  651 + );
  652 + }
  653 +
  654 + /**
  655 + * Send an SMTP RSET command.
  656 + * Abort any transaction that is currently in progress.
  657 + * Implements rfc 821: RSET <CRLF>
  658 + * @access public
  659 + * @return bool True on success.
  660 + */
  661 + public function reset()
  662 + {
  663 + return $this->sendCommand('RSET', 'RSET', 250);
  664 + }
  665 +
  666 + /**
  667 + * Send a command to an SMTP server and check its return code.
  668 + * @param string $command The command name - not sent to the server
  669 + * @param string $commandstring The actual command to send
  670 + * @param int|array $expect One or more expected integer success codes
  671 + * @access protected
  672 + * @return bool True on success.
  673 + */
  674 + protected function sendCommand($command, $commandstring, $expect)
  675 + {
  676 + if (!$this->connected()) {
  677 + $this->error = array(
  678 + 'error' => "Called $command without being connected"
  679 + );
  680 + return false;
  681 + }
  682 + $this->client_send($commandstring . self::CRLF);
  683 +
  684 + $reply = $this->get_lines();
  685 + $code = substr($reply, 0, 3);
  686 +
  687 + if ($this->do_debug >= 2) {
  688 + $this->edebug('SERVER -> CLIENT: ' . $reply);
  689 + }
  690 +
  691 + if (!in_array($code, (array)$expect)) {
  692 + $this->last_reply = null;
  693 + $this->error = array(
  694 + 'error' => "$command command failed",
  695 + 'smtp_code' => $code,
  696 + 'detail' => substr($reply, 4)
  697 + );
  698 + if ($this->do_debug >= 1) {
  699 + $this->edebug(
  700 + 'SMTP ERROR: ' . $this->error['error'] . ': ' . $reply
  701 + );
  702 + }
  703 + return false;
  704 + }
  705 +
  706 + $this->last_reply = $reply;
  707 + $this->error = null;
  708 + return true;
  709 + }
  710 +
  711 + /**
  712 + * Send an SMTP SAML command.
  713 + * Starts a mail transaction from the email address specified in $from.
  714 + * Returns true if successful or false otherwise. If True
  715 + * the mail transaction is started and then one or more recipient
  716 + * commands may be called followed by a data command. This command
  717 + * will send the message to the users terminal if they are logged
  718 + * in and send them an email.
  719 + * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
  720 + * @param string $from The address the message is from
  721 + * @access public
  722 + * @return bool
  723 + */
  724 + public function sendAndMail($from)
  725 + {
  726 + return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  727 + }
  728 +
  729 + /**
  730 + * Send an SMTP VRFY command.
  731 + * @param string $name The name to verify
  732 + * @access public
  733 + * @return bool
  734 + */
  735 + public function verify($name)
  736 + {
  737 + return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
  738 + }
  739 +
  740 + /**
  741 + * Send an SMTP NOOP command.
  742 + * Used to keep keep-alives alive, doesn't actually do anything
  743 + * @access public
  744 + * @return bool
  745 + */
  746 + public function noop()
  747 + {
  748 + return $this->sendCommand('NOOP', 'NOOP', 250);
  749 + }
  750 +
  751 + /**
  752 + * Send an SMTP TURN command.
  753 + * This is an optional command for SMTP that this class does not support.
  754 + * This method is here to make the RFC821 Definition complete for this class
  755 + * and _may_ be implemented in future
  756 + * Implements from rfc 821: TURN <CRLF>
  757 + * @access public
  758 + * @return bool
  759 + */
  760 + public function turn()
  761 + {
  762 + $this->error = array(
  763 + 'error' => 'The SMTP TURN command is not implemented'
  764 + );
  765 + if ($this->do_debug >= 1) {
  766 + $this->edebug('SMTP NOTICE: ' . $this->error['error']);
  767 + }
  768 + return false;
  769 + }
  770 +
  771 + /**
  772 + * Send raw data to the server.
  773 + * @param string $data The data to send
  774 + * @access public
  775 + * @return int|bool The number of bytes sent to the server or false on error
  776 + */
  777 + public function client_send($data)
  778 + {
  779 + if ($this->do_debug >= 1) {
  780 + $this->edebug("CLIENT -> SERVER: $data");
  781 + }
  782 + return fwrite($this->smtp_conn, $data);
  783 + }
  784 +
  785 + /**
  786 + * Get the latest error.
  787 + * @access public
  788 + * @return array
  789 + */
  790 + public function getError()
  791 + {
  792 + return $this->error;
  793 + }
  794 +
  795 + /**
  796 + * Get the last reply from the server.
  797 + * @access public
  798 + * @return string
  799 + */
  800 + public function getLastReply()
  801 + {
  802 + return $this->last_reply;
  803 + }
  804 +
  805 + /**
  806 + * Read the SMTP server's response.
  807 + * Either before eof or socket timeout occurs on the operation.
  808 + * With SMTP we can tell if we have more lines to read if the
  809 + * 4th character is '-' symbol. If it is a space then we don't
  810 + * need to read anything else.
  811 + * @access protected
  812 + * @return string
  813 + */
  814 + protected function get_lines()
  815 + {
  816 + // If the connection is bad, give up straight away
  817 + if (!is_resource($this->smtp_conn)) {
  818 + return '';
  819 + }
  820 + $data = '';
  821 + $endtime = 0;
  822 + stream_set_timeout($this->smtp_conn, $this->Timeout);
  823 + if ($this->Timelimit > 0) {
  824 + $endtime = time() + $this->Timelimit;
  825 + }
  826 + while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
  827 + $str = @fgets($this->smtp_conn, 515);
  828 + if ($this->do_debug >= 4) {
  829 + $this->edebug("SMTP -> get_lines(): \$data was \"$data\"");
  830 + $this->edebug("SMTP -> get_lines(): \$str is \"$str\"");
  831 + }
  832 + $data .= $str;
  833 + if ($this->do_debug >= 4) {
  834 + $this->edebug("SMTP -> get_lines(): \$data is \"$data\"");
  835 + }
  836 + // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen
  837 + if ((isset($str[3]) and $str[3] == ' ')) {
  838 + break;
  839 + }
  840 + // Timed-out? Log and break
  841 + $info = stream_get_meta_data($this->smtp_conn);
  842 + if ($info['timed_out']) {
  843 + if ($this->do_debug >= 4) {
  844 + $this->edebug(
  845 + 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)'
  846 + );
  847 + }
  848 + break;
  849 + }
  850 + // Now check if reads took too long
  851 + if ($endtime and time() > $endtime) {
  852 + if ($this->do_debug >= 4) {
  853 + $this->edebug(
  854 + 'SMTP -> get_lines(): timelimit reached ('.
  855 + $this->Timelimit . ' sec)'
  856 + );
  857 + }
  858 + break;
  859 + }
  860 + }
  861 + return $data;
  862 + }
  863 +
  864 + /**
  865 + * Enable or disable VERP address generation.
  866 + * @param bool $enabled
  867 + */
  868 + public function setVerp($enabled = false)
  869 + {
  870 + $this->do_verp = $enabled;
  871 + }
  872 +
  873 + /**
  874 + * Get VERP address generation mode.
  875 + * @return bool
  876 + */
  877 + public function getVerp()
  878 + {
  879 + return $this->do_verp;
  880 + }
  881 +
  882 + /**
  883 + * Set debug output method.
  884 + * @param string $method The function/method to use for debugging output.
  885 + */
  886 + public function setDebugOutput($method = 'echo')
  887 + {
  888 + $this->Debugoutput = $method;
  889 + }
  890 +
  891 + /**
  892 + * Get debug output method.
  893 + * @return string
  894 + */
  895 + public function getDebugOutput()
  896 + {
  897 + return $this->Debugoutput;
  898 + }
  899 +
  900 + /**
  901 + * Set debug output level.
  902 + * @param int $level
  903 + */
  904 + public function setDebugLevel($level = 0)
  905 + {
  906 + $this->do_debug = $level;
  907 + }
  908 +
  909 + /**
  910 + * Get debug output level.
  911 + * @return int
  912 + */
  913 + public function getDebugLevel()
  914 + {
  915 + return $this->do_debug;
  916 + }
  917 +
  918 + /**
  919 + * Set SMTP timeout.
  920 + * @param int $timeout
  921 + */
  922 + public function setTimeout($timeout = 0)
  923 + {
  924 + $this->Timeout = $timeout;
  925 + }
  926 +
  927 + /**
  928 + * Get SMTP timeout.
  929 + * @return int
  930 + */
  931 + public function getTimeout()
  932 + {
  933 + return $this->Timeout;
  934 + }
  935 +}
... ...
  1 +{
  2 + "name": "phpmailer/phpmailer",
  3 + "type": "library",
  4 + "description": "PHPMailer is a full-featured email creation and transfer class for PHP",
  5 + "authors": [
  6 + {
  7 + "name": "Marcus Bointon",
  8 + "email": "phpmailer@synchromedia.co.uk"
  9 + },
  10 + {
  11 + "name": "Jim Jagielski",
  12 + "email": "jimjag@gmail.com"
  13 + },
  14 + {
  15 + "name": "Andy Prevost",
  16 + "email": "codeworxtech@users.sourceforge.net"
  17 + },
  18 + {
  19 + "name": "Brent R. Matzelle"
  20 + }
  21 + ],
  22 + "require": {
  23 + "php": ">=5.0.0"
  24 + },
  25 + "require-dev": {
  26 + "phpdocumentor/phpdocumentor": "*",
  27 + "phpunit/phpunit": "4.0.*"
  28 + },
  29 + "autoload": {
  30 + "classmap": ["class.phpmailer.php", "class.pop3.php", "class.smtp.php"]
  31 + },
  32 + "license": "LGPL-2.1"
  33 +}
\ No newline at end of file
... ...
  1 +NEW CALLBACK FUNCTION:
  2 +======================
  3 +
  4 +We have had requests for a method to process the results of sending emails
  5 +through PHPMailer. In this new release, we have implemented a callback
  6 +function that passes the results of each email sent (to, cc, and/or bcc).
  7 +We have provided an example that echos the results back to the screen. The
  8 +callback function can be used for any purpose. With minor modifications, the
  9 +callback function can be used to create CSV logs, post results to databases,
  10 +etc.
  11 +
  12 +Please review the test.php script for the example.
  13 +
  14 +It's pretty straight forward.
  15 +
  16 +Enjoy!
  17 +Andy
... ...
  1 +CREATE DKIM KEYS and DNS Resource Record:
  2 +=========================================
  3 +
  4 +To create DomainKeys Identified Mail keys, visit:
  5 +http://dkim.worxware.com/
  6 +... read the information, fill in the form, and download the ZIP file
  7 +containing the public key, private key, DNS Resource Record and instructions
  8 +to add to your DNS Zone Record, and the PHPMailer code to enable DKIM
  9 +digital signing.
  10 +
  11 +/*** PROTECT YOUR PRIVATE & PUBLIC KEYS ***/
  12 +
  13 +You need to protect your DKIM private and public keys from being viewed or
  14 +accessed. Add protection to your .htaccess file as in this example:
  15 +
  16 +# secure htkeyprivate file
  17 +<Files .htkeyprivate>
  18 + order allow,deny
  19 + deny from all
  20 +</Files>
  21 +
  22 +# secure htkeypublic file
  23 +<Files .htkeypublic>
  24 + order allow,deny
  25 + deny from all
  26 +</Files>
  27 +
  28 +(the actual .htaccess additions are in the ZIP file sent back to you from
  29 +http://dkim.worxware.com/
  30 +
  31 +A few notes on using DomainKey Identified Mail (DKIM):
  32 +
  33 +You do not need to use PHPMailer to DKIM sign emails IF:
  34 +- you enable DomainKey support and add the DNS resource record
  35 +- you use your outbound mail server
  36 +
  37 +If you are a third-party emailer that works on behalf of domain owners to
  38 +send their emails from your own server:
  39 +- you absolutely have to DKIM sign outbound emails
  40 +- the domain owner has to add the DNS resource record to match the
  41 + private key, public key, selector, identity, and domain that you create
  42 +- use caution with the "selector" ... at least one "selector" will already
  43 + exist in the DNS Zone Record of the domain at the domain owner's server
  44 + you need to ensure that the "selector" you use is unique
  45 +Note: since the IP address will not match the domain owner's DNS Zone record
  46 +you can be certain that email providers that validate based on DomainKey will
  47 +check the domain owner's DNS Zone record for your DNS resource record. Before
  48 +sending out emails on behalf of domain owners, ensure they have entered the
  49 +DNS resource record you provided them.
  50 +
  51 +Enjoy!
  52 +Andy
  53 +
  54 +PS. if you need additional information about DKIM, please see:
  55 +http://www.dkim.org/info/dkim-faq.html
... ...
  1 +If you are having problems connecting or sending emails through your SMTP server, the SMTP class can provide more information about the processing/errors taking place.
  2 +Use the debug functionality of the class to see what's going on in your connections. To do that, set the debug level in your script. For example:
  3 +
  4 +$mail->SMTPDebug = 1;
  5 +$mail->isSMTP(); // telling the class to use SMTP
  6 +$mail->SMTPAuth = true; // enable SMTP authentication
  7 +$mail->Port = 26; // set the SMTP port
  8 +$mail->Host = "mail.yourhost.com"; // SMTP server
  9 +$mail->Username = "name@yourhost.com"; // SMTP account username
  10 +$mail->Password = "your password"; // SMTP account password
  11 +
  12 +Notes on this:
  13 +$mail->SMTPDebug = 0; ... will disable debugging (you can also leave this out completely, 0 is the default)
  14 +$mail->SMTPDebug = 1; ... will echo errors and server responses
  15 +$mail->SMTPDebug = 2; ... will echo errors, server responses and client messages
  16 +
  17 +And finally, don't forget to disable debugging before going into production.
... ...
  1 +<html>
  2 +<head>
  3 +<title>Examples using phpmailer</title>
  4 +</head>
  5 +
  6 +<body>
  7 +
  8 +<h2>Examples using PHPMailer</h2>
  9 +
  10 +<h3>1. Advanced Example</h3>
  11 +<p>
  12 +
  13 +This demonstrates sending multiple email messages with binary attachments
  14 +from a MySQL database using multipart/alternative messages.<p>
  15 +
  16 +<pre>
  17 +require 'PHPMailerAutoload.php';
  18 +
  19 +$mail = new PHPMailer();
  20 +
  21 +$mail->From = 'list@example.com';
  22 +$mail->FromName = 'List manager';
  23 +$mail->Host = 'smtp1.example.com;smtp2.example.com';
  24 +$mail->Mailer = 'smtp';
  25 +
  26 +@mysqli_connect('localhost','root','password');
  27 +@mysqli_select_db("my_company");
  28 +$query = "SELECT full_name, email, photo FROM employee";
  29 +$result = @mysqli_query($query);
  30 +
  31 +while ($row = mysqli_fetch_assoc($result))
  32 +{
  33 + // HTML body
  34 + $body = "Hello &lt;font size=\"4\"&gt;" . $row['full_name'] . "&lt;/font&gt;, &lt;p&gt;";
  35 + $body .= "&lt;i&gt;Your&lt;/i&gt; personal photograph to this message.&lt;p&gt;";
  36 + $body .= "Sincerely, &lt;br&gt;";
  37 + $body .= "phpmailer List manager";
  38 +
  39 + // Plain text body (for mail clients that cannot read HTML)
  40 + $text_body = 'Hello ' . $row['full_name'] . ", \n\n";
  41 + $text_body .= "Your personal photograph to this message.\n\n";
  42 + $text_body .= "Sincerely, \n";
  43 + $text_body .= 'phpmailer List manager';
  44 +
  45 + $mail->Body = $body;
  46 + $mail->AltBody = $text_body;
  47 + $mail->addAddress($row['email'], $row['full_name']);
  48 + $mail->addStringAttachment($row['photo'], 'YourPhoto.jpg');
  49 +
  50 + if(!$mail->send())
  51 + echo "There has been a mail error sending to " . $row['email'] . "&lt;br&gt;";
  52 +
  53 + // Clear all addresses and attachments for next loop
  54 + $mail->clearAddresses();
  55 + $mail->clearAttachments();
  56 +}
  57 +</pre>
  58 +<p>
  59 +
  60 +<h3>2. Extending PHPMailer</h3>
  61 +<p>
  62 +
  63 +Extending classes with inheritance is one of the most
  64 +powerful features of object-oriented programming. It allows you to make changes to the
  65 +original class for your own personal use without hacking the original
  66 +classes, and it's very easy to do:
  67 +
  68 +<p>
  69 +Here's a class that extends the phpmailer class and sets the defaults
  70 +for the particular site:<br>
  71 +PHP include file: my_phpmailer.php
  72 +<p>
  73 +
  74 +<pre>
  75 +require 'PHPMailerAutoload.php';
  76 +
  77 +class my_phpmailer extends PHPMailer {
  78 + // Set default variables for all new objects
  79 + public $From = 'from@example.com';
  80 + public $FromName = 'Mailer';
  81 + public $Host = 'smtp1.example.com;smtp2.example.com';
  82 + public $Mailer = 'smtp'; // Alternative to isSMTP()
  83 + public $WordWrap = 75;
  84 +
  85 + // Replace the default debug output function
  86 + protected function edebug($msg) {
  87 + print('My Site Error');
  88 + print('Description:');
  89 + printf('%s', $msg);
  90 + exit;
  91 + }
  92 +
  93 + //Extend the send function
  94 + public function send() {
  95 + $this->Subject = '[Yay for me!] '.$this->Subject;
  96 + return parent::send()
  97 + }
  98 +
  99 + // Create an additional function
  100 + public function do_something($something) {
  101 + // Place your new code here
  102 + }
  103 +}
  104 +</pre>
  105 +<br>
  106 +Now here's a normal PHP page in the site, which will have all the defaults set above:<br>
  107 +
  108 +<pre>
  109 +require 'my_phpmailer.php';
  110 +
  111 +// Instantiate your new class
  112 +$mail = new my_phpmailer;
  113 +
  114 +// Now you only need to add the necessary stuff
  115 +$mail->addAddress('josh@example.com', 'Josh Adams');
  116 +$mail->Subject = 'Here is the subject';
  117 +$mail->Body = 'This is the message body';
  118 +$mail->addAttachment('c:/temp/11-10-00.zip', 'new_name.zip'); // optional name
  119 +
  120 +if(!$mail->send())
  121 +{
  122 + echo 'There was an error sending the message';
  123 + exit;
  124 +}
  125 +
  126 +echo 'Message was sent successfully';
  127 +</pre>
  128 +</body>
  129 +</html>
... ...
  1 +<html>
  2 +<head>
  3 +<title>PHPMailer FAQ</title>
  4 +</head>
  5 +<body>
  6 +<h2>PHPMailer FAQ</h2>
  7 +<ul>
  8 + <li><strong>Q: I am concerned that using include files will take up too much
  9 + processing time on my computer. How can I make it run faster?</strong><br>
  10 + <strong>A:</strong> PHP by itself is fairly fast, but it recompiles scripts every time they are run, which takes up valuable
  11 + computer resources. You can bypass this by using an opcode cache which compiles
  12 + PHP code and store it in memory to reduce overhead immensely. <a href="http://www.php.net/apc/">APC
  13 + (Alternative PHP Cache)</a> is a free opcode cache extension in the PECL library.</li>
  14 + <li><strong>Q: Which mailer gives me the best performance?</strong><br>
  15 + <strong>A:</strong> On a single machine the <strong>sendmail (or Qmail)</strong> is fastest overall.
  16 + Next fastest is mail() to give you the best performance. Both do not have the overhead of SMTP.
  17 + If you do not have a local mail server (as is typical on Windows), SMTP is your only option.</li>
  18 + <li><strong>Q: When I try to attach a file with on my server I get a
  19 + "Could not find {file} on filesystem error". Why is this?</strong><br>
  20 + <strong>A:</strong> If you are using a Unix machine this is probably because the user
  21 + running your web server does not have read access to the directory in question. If you are using Windows,
  22 + then the problem is probably that you have used single backslashes to denote directories (\).
  23 + A single backslash has a special meaning to PHP so these are not
  24 + valid. Instead use double backslashes ("\\") or a single forward
  25 + slash ("/").</li>
  26 +</ul>
  27 +</body>
  28 +</html>
... ...
  1 +#!/bin/sh
  2 +# Regenerate PHPMailer documentation
  3 +# Run from within the docs folder
  4 +rm -rf phpdoc/*
  5 +phpdoc --directory .. --target ./phpdoc --ignore test/,examples/,extras/,test_script/ --sourcecode --force --title PHPMailer --template="clean"
... ...
  1 +This is built for PHP Mailer 1.72 and was not tested with any previous version. It was developed under PHP 4.3.11 (E_ALL). It works under PHP 5 and 5.1 with E_ALL, but not in Strict mode due to var deprecation (but then neither does PHP Mailer either!). It follows the RFC 1939 standard explicitly and is fully commented.
  2 +
  3 +With that noted, here is how to implement it:
  4 +
  5 +I didn't want to modify the PHP Mailer classes at all, so you will have to include/require this class along with the base one. It can sit quite happily in the phpmailer directory.
  6 +
  7 +When you need it, create your POP3 object
  8 +
  9 +Right before I invoke PHP Mailer I activate the POP3 authorisation. POP3 before SMTP is a process whereby you login to your web hosts POP3 mail server BEFORE sending out any emails via SMTP. The POP3 logon 'verifies' your ability to send email by SMTP, which typically otherwise blocks you. On my web host (Pair Networks) a single POP3 logon is enough to 'verify' you for 90 minutes. Here is some sample PHP code that activates the POP3 logon and then sends an email via PHP Mailer:
  10 +
  11 +<?php
  12 +$pop->authorise('pop3.example.com', 110, 30, 'mailer', 'password', 1);
  13 +$mail = new PHPMailer(); $mail->SMTPDebug = 2; $mail->isSMTP();
  14 +$mail->isHTML(false); $mail->Host = 'relay.example.com';
  15 +$mail->From = 'mailer@example.com';
  16 +$mail->FromName = 'Example Mailer';
  17 +$mail->Subject = 'My subject';
  18 +$mail->Body = 'Hello world';
  19 +$mail->addAddress('rich@corephp.co.uk', 'Richard Davey');
  20 +if (!$mail->send()) {
  21 + echo $mail->ErrorInfo;
  22 +}
  23 +?>
  24 +
  25 +The PHP Mailer parts of this code should be obvious to anyone who has used PHP Mailer before. One thing to note - you almost certainly will not need to use SMTP Authentication *and* POP3 before SMTP together. The Authorisation method is a proxy method to all of the others within that class. There are connect, Logon and disconnect methods available, but I wrapped them in the single Authorisation one to make things easier.
  26 +The Parameters
  27 +
  28 +The authorise parameters are as follows:
  29 +
  30 +$pop->authorise('pop3.example.com', 110, 30, 'mailer', 'password', 1);
  31 +
  32 + 1. pop3.example.com - The POP3 Mail Server Name (hostname or IP address)
  33 + 2. 110 - The POP3 Port on which to connect (default is usually 110, but check with your host)
  34 + 3. 30 - A connection time-out value (in seconds)
  35 + 4. mailer - The POP3 Username required to logon
  36 + 5. password - The POP3 Password required to logon
  37 + 6. 1 - The class debug level (0 = off, 1+ = debug output is echoed to the browser)
  38 +
  39 +Final Comments + the Download
  40 +
  41 +1) This class does not support APOP connections. This is only because I did not have an APOP server to test with, but if you'd like to see that added just contact me.
  42 +
  43 +2) Opening and closing lots of POP3 connections can be quite a resource/network drain. If you need to send a whole batch of emails then just perform the authentication once at the start, and then loop through your mail sending script. Providing this process doesn't take longer than the verification period lasts on your POP3 server, you should be fine. With my host that period is 90 minutes, i.e. plenty of time.
  44 +
  45 +3) If you have heavy requirements for this script (i.e. send a LOT of email on a frequent basis) then I would advise seeking out an alternative sending method (direct SMTP ideally). If this isn't possible then you could modify this class so the 'last authorised' date is recorded somewhere (MySQL, Flat file, etc) meaning you only open a new connection if the old one has expired, saving you precious overhead.
  46 +
  47 +4) There are lots of other POP3 classes for PHP available. However most of them implement the full POP3 command set, where-as this one is purely for authentication, and much lighter as a result. However using any of the other POP3 classes to just logon to your server would have the same net result. At the end of the day, use whatever method you feel most comfortable with.
  48 +Download
  49 +
  50 +My thanks to Chris Ryan for the inspiration (even if indirectly, via his SMTP class)
... ...
  1 + GNU LESSER GENERAL PUBLIC LICENSE
  2 + Version 3, 29 June 2007
  3 +
  4 + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
  5 + Everyone is permitted to copy and distribute verbatim copies
  6 + of this license document, but changing it is not allowed.
  7 +
  8 +
  9 + This version of the GNU Lesser General Public License incorporates
  10 +the terms and conditions of version 3 of the GNU General Public
  11 +License, supplemented by the additional permissions listed below.
  12 +
  13 + 0. Additional Definitions.
  14 +
  15 + As used herein, "this License" refers to version 3 of the GNU Lesser
  16 +General Public License, and the "GNU GPL" refers to version 3 of the GNU
  17 +General Public License.
  18 +
  19 + "The Library" refers to a covered work governed by this License,
  20 +other than an Application or a Combined Work as defined below.
  21 +
  22 + An "Application" is any work that makes use of an interface provided
  23 +by the Library, but which is not otherwise based on the Library.
  24 +Defining a subclass of a class defined by the Library is deemed a mode
  25 +of using an interface provided by the Library.
  26 +
  27 + A "Combined Work" is a work produced by combining or linking an
  28 +Application with the Library. The particular version of the Library
  29 +with which the Combined Work was made is also called the "Linked
  30 +Version".
  31 +
  32 + The "Minimal Corresponding Source" for a Combined Work means the
  33 +Corresponding Source for the Combined Work, excluding any source code
  34 +for portions of the Combined Work that, considered in isolation, are
  35 +based on the Application, and not on the Linked Version.
  36 +
  37 + The "Corresponding Application Code" for a Combined Work means the
  38 +object code and/or source code for the Application, including any data
  39 +and utility programs needed for reproducing the Combined Work from the
  40 +Application, but excluding the System Libraries of the Combined Work.
  41 +
  42 + 1. Exception to Section 3 of the GNU GPL.
  43 +
  44 + You may convey a covered work under sections 3 and 4 of this License
  45 +without being bound by section 3 of the GNU GPL.
  46 +
  47 + 2. Conveying Modified Versions.
  48 +
  49 + If you modify a copy of the Library, and, in your modifications, a
  50 +facility refers to a function or data to be supplied by an Application
  51 +that uses the facility (other than as an argument passed when the
  52 +facility is invoked), then you may convey a copy of the modified
  53 +version:
  54 +
  55 + a) under this License, provided that you make a good faith effort to
  56 + ensure that, in the event an Application does not supply the
  57 + function or data, the facility still operates, and performs
  58 + whatever part of its purpose remains meaningful, or
  59 +
  60 + b) under the GNU GPL, with none of the additional permissions of
  61 + this License applicable to that copy.
  62 +
  63 + 3. Object Code Incorporating Material from Library Header Files.
  64 +
  65 + The object code form of an Application may incorporate material from
  66 +a header file that is part of the Library. You may convey such object
  67 +code under terms of your choice, provided that, if the incorporated
  68 +material is not limited to numerical parameters, data structure
  69 +layouts and accessors, or small macros, inline functions and templates
  70 +(ten or fewer lines in length), you do both of the following:
  71 +
  72 + a) Give prominent notice with each copy of the object code that the
  73 + Library is used in it and that the Library and its use are
  74 + covered by this License.
  75 +
  76 + b) Accompany the object code with a copy of the GNU GPL and this license
  77 + document.
  78 +
  79 + 4. Combined Works.
  80 +
  81 + You may convey a Combined Work under terms of your choice that,
  82 +taken together, effectively do not restrict modification of the
  83 +portions of the Library contained in the Combined Work and reverse
  84 +engineering for debugging such modifications, if you also do each of
  85 +the following:
  86 +
  87 + a) Give prominent notice with each copy of the Combined Work that
  88 + the Library is used in it and that the Library and its use are
  89 + covered by this License.
  90 +
  91 + b) Accompany the Combined Work with a copy of the GNU GPL and this license
  92 + document.
  93 +
  94 + c) For a Combined Work that displays copyright notices during
  95 + execution, include the copyright notice for the Library among
  96 + these notices, as well as a reference directing the user to the
  97 + copies of the GNU GPL and this license document.
  98 +
  99 + d) Do one of the following:
  100 +
  101 + 0) Convey the Minimal Corresponding Source under the terms of this
  102 + License, and the Corresponding Application Code in a form
  103 + suitable for, and under terms that permit, the user to
  104 + recombine or relink the Application with a modified version of
  105 + the Linked Version to produce a modified Combined Work, in the
  106 + manner specified by section 6 of the GNU GPL for conveying
  107 + Corresponding Source.
  108 +
  109 + 1) Use a suitable shared library mechanism for linking with the
  110 + Library. A suitable mechanism is one that (a) uses at run time
  111 + a copy of the Library already present on the user's computer
  112 + system, and (b) will operate properly with a modified version
  113 + of the Library that is interface-compatible with the Linked
  114 + Version.
  115 +
  116 + e) Provide Installation Information, but only if you would otherwise
  117 + be required to provide such information under section 6 of the
  118 + GNU GPL, and only to the extent that such information is
  119 + necessary to install and execute a modified version of the
  120 + Combined Work produced by recombining or relinking the
  121 + Application with a modified version of the Linked Version. (If
  122 + you use option 4d0, the Installation Information must accompany
  123 + the Minimal Corresponding Source and Corresponding Application
  124 + Code. If you use option 4d1, you must provide the Installation
  125 + Information in the manner specified by section 6 of the GNU GPL
  126 + for conveying Corresponding Source.)
  127 +
  128 + 5. Combined Libraries.
  129 +
  130 + You may place library facilities that are a work based on the
  131 +Library side by side in a single library together with other library
  132 +facilities that are not Applications and are not covered by this
  133 +License, and convey such a combined library under terms of your
  134 +choice, if you do both of the following:
  135 +
  136 + a) Accompany the combined library with a copy of the same work based
  137 + on the Library, uncombined with any other library facilities,
  138 + conveyed under the terms of this License.
  139 +
  140 + b) Give prominent notice with the combined library that part of it
  141 + is a work based on the Library, and explaining where to find the
  142 + accompanying uncombined form of the same work.
  143 +
  144 + 6. Revised Versions of the GNU Lesser General Public License.
  145 +
  146 + The Free Software Foundation may publish revised and/or new versions
  147 +of the GNU Lesser General Public License from time to time. Such new
  148 +versions will be similar in spirit to the present version, but may
  149 +differ in detail to address new problems or concerns.
  150 +
  151 + Each version is given a distinguishing version number. If the
  152 +Library as you received it specifies that a certain numbered version
  153 +of the GNU Lesser General Public License "or any later version"
  154 +applies to it, you have the option of following the terms and
  155 +conditions either of that published version or of any later version
  156 +published by the Free Software Foundation. If the Library as you
  157 +received it does not specify a version number of the GNU Lesser
  158 +General Public License, you may choose any version of the GNU Lesser
  159 +General Public License ever published by the Free Software Foundation.
  160 +
  161 + If the Library as you received it specifies that a proxy can decide
  162 +whether future versions of the GNU Lesser General Public License shall
  163 +apply, that proxy's public statement of acceptance of any version is
  164 +permanent authorization for you to choose that version for the
  165 +Library.
\ No newline at end of file
... ...
  1 +<?php
  2 +/*
  3 +* revised, updated and corrected 27/02/2013
  4 +* by matt.sturdy@gmail.com
  5 +*/
  6 +require '../PHPMailerAutoload.php';
  7 +
  8 +$CFG['smtp_debug'] = 2; //0 == off, 1 for client output, 2 for client and server
  9 +$CFG['smtp_debugoutput'] = 'html';
  10 +$CFG['smtp_server'] = 'localhost';
  11 +$CFG['smtp_port'] = '25';
  12 +$CFG['smtp_authenticate'] = false;
  13 +$CFG['smtp_username'] = 'name@example.com';
  14 +$CFG['smtp_password'] = 'yourpassword';
  15 +$CFG['smtp_secure'] = 'None';
  16 +
  17 +$from_name = (isset($_POST['From_Name'])) ? $_POST['From_Name'] : '';
  18 +$from_email = (isset($_POST['From_Email'])) ? $_POST['From_Email'] : '';
  19 +$to_name = (isset($_POST['To_Name'])) ? $_POST['To_Name'] : '';
  20 +$to_email = (isset($_POST['To_Email'])) ? $_POST['To_Email'] : '';
  21 +$cc_email = (isset($_POST['cc_Email'])) ? $_POST['cc_Email'] : '';
  22 +$bcc_email = (isset($_POST['bcc_Email'])) ? $_POST['bcc_Email'] : '';
  23 +$subject = (isset($_POST['Subject'])) ? $_POST['Subject'] : '';
  24 +$message = (isset($_POST['Message'])) ? $_POST['Message'] : '';
  25 +$test_type = (isset($_POST['test_type'])) ? $_POST['test_type'] : 'smtp';
  26 +$smtp_debug = (isset($_POST['smtp_debug'])) ? $_POST['smtp_debug'] : $CFG['smtp_debug'];
  27 +$smtp_server = (isset($_POST['smtp_server'])) ? $_POST['smtp_server'] : $CFG['smtp_server'];
  28 +$smtp_port = (isset($_POST['smtp_port'])) ? $_POST['smtp_port'] : $CFG['smtp_port'];
  29 +$smtp_secure = strtolower((isset($_POST['smtp_secure'])) ? $_POST['smtp_secure'] : $CFG['smtp_secure']);
  30 +$smtp_authenticate = (isset($_POST['smtp_authenticate'])) ?
  31 + $_POST['smtp_authenticate'] : $CFG['smtp_authenticate'];
  32 +$authenticate_password = (isset($_POST['authenticate_password'])) ?
  33 + $_POST['authenticate_password'] : $CFG['smtp_password'];
  34 +$authenticate_username = (isset($_POST['authenticate_username'])) ?
  35 + $_POST['authenticate_username'] : $CFG['smtp_username'];
  36 +
  37 +// storing all status output from the script to be shown to the user later
  38 +$results_messages = array();
  39 +
  40 +// $example_code represents the "final code" that we're using, and will
  41 +// be shown to the user at the end.
  42 +$example_code = "\nrequire_once '../PHPMailerAutoload.php';";
  43 +$example_code .= "\n\n\$results_messages = array();";
  44 +
  45 +$mail = new PHPMailer(true); //PHPMailer instance with exceptions enabled
  46 +$mail->CharSet = 'utf-8';
  47 +$mail->Debugoutput = $CFG['smtp_debugoutput'];
  48 +$example_code .= "\n\n\$mail = new PHPMailer(true);";
  49 +$example_code .= "\n\$mail->CharSet = 'utf-8';";
  50 +
  51 +class phpmailerAppException extends phpmailerException
  52 +{
  53 +}
  54 +
  55 +$example_code .= "\n\nclass phpmailerAppException extends phpmailerException {}";
  56 +$example_code .= "\n\ntry {";
  57 +
  58 +try {
  59 + if (isset($_POST["submit"]) && $_POST['submit'] == "Submit") {
  60 + $to = $_POST['To_Email'];
  61 + if (!PHPMailer::validateAddress($to)) {
  62 + throw new phpmailerAppException("Email address " . $to . " is invalid -- aborting!");
  63 + }
  64 +
  65 + $example_code .= "\n\$to = '{$_POST['To_Email']}';";
  66 + $example_code .= "\nif(!PHPMailer::validateAddress(\$to)) {";
  67 + $example_code .= "\n throw new phpmailerAppException(\"Email address \" . " .
  68 + "\$to . \" is invalid -- aborting!\");";
  69 + $example_code .= "\n}";
  70 +
  71 + switch ($_POST['test_type']) {
  72 + case 'smtp':
  73 + $mail->isSMTP(); // telling the class to use SMTP
  74 + $mail->SMTPDebug = (integer)$_POST['smtp_debug'];
  75 + $mail->Host = $_POST['smtp_server']; // SMTP server
  76 + $mail->Port = (integer)$_POST['smtp_port']; // set the SMTP port
  77 + if ($_POST['smtp_secure']) {
  78 + $mail->SMTPSecure = strtolower($_POST['smtp_secure']);
  79 + }
  80 + $mail->SMTPAuth = array_key_exists('smtp_authenticate', $_POST); // enable SMTP authentication?
  81 + if (array_key_exists('smtp_authenticate', $_POST)) {
  82 + $mail->Username = $_POST['authenticate_username']; // SMTP account username
  83 + $mail->Password = $_POST['authenticate_password']; // SMTP account password
  84 + }
  85 +
  86 + $example_code .= "\n\$mail->isSMTP();";
  87 + $example_code .= "\n\$mail->SMTPDebug = " . $_POST['smtp_debug'] . ";";
  88 + $example_code .= "\n\$mail->Host = \"" . $_POST['smtp_server'] . "\";";
  89 + $example_code .= "\n\$mail->Port = \"" . $_POST['smtp_port'] . "\";";
  90 + $example_code .= "\n\$mail->SMTPSecure = \"" . strtolower($_POST['smtp_secure']) . "\";";
  91 + $example_code .= "\n\$mail->SMTPAuth = " . (array_key_exists(
  92 + 'smtp_authenticate',
  93 + $_POST
  94 + ) ? 'true' : 'false') . ";";
  95 + if (array_key_exists('smtp_authenticate', $_POST)) {
  96 + $example_code .= "\n\$mail->Username = \"" . $_POST['authenticate_username'] . "\";";
  97 + $example_code .= "\n\$mail->Password = \"" . $_POST['authenticate_password'] . "\";";
  98 + }
  99 + break;
  100 + case 'mail':
  101 + $mail->isMail(); // telling the class to use PHP's mail()
  102 + $example_code .= "\n\$mail->isMail();";
  103 + break;
  104 + case 'sendmail':
  105 + $mail->isSendmail(); // telling the class to use Sendmail
  106 + $example_code .= "\n\$mail->isSendmail();";
  107 + break;
  108 + case 'qmail':
  109 + $mail->isQmail(); // telling the class to use Qmail
  110 + $example_code .= "\n\$mail->isQmail();";
  111 + break;
  112 + default:
  113 + throw new phpmailerAppException('Invalid test_type provided');
  114 + }
  115 +
  116 + try {
  117 + if ($_POST['From_Name'] != '') {
  118 + $mail->addReplyTo($_POST['From_Email'], $_POST['From_Name']);
  119 + $mail->From = $_POST['From_Email'];
  120 + $mail->FromName = $_POST['From_Name'];
  121 +
  122 + $example_code .= "\n\$mail->addReplyTo(\"" .
  123 + $_POST['From_Email'] . "\", \"" . $_POST['From_Name'] . "\");";
  124 + $example_code .= "\n\$mail->From = \"" . $_POST['From_Email'] . "\";";
  125 + $example_code .= "\n\$mail->FromName = \"" . $_POST['From_Name'] . "\";";
  126 + } else {
  127 + $mail->addReplyTo($_POST['From_Email']);
  128 + $mail->From = $_POST['From_Email'];
  129 + $mail->FromName = $_POST['From_Email'];
  130 +
  131 + $example_code .= "\n\$mail->addReplyTo(\"" . $_POST['From_Email'] . "\");";
  132 + $example_code .= "\n\$mail->From = \"" . $_POST['From_Email'] . "\";";
  133 + $example_code .= "\n\$mail->FromName = \"" . $_POST['From_Email'] . "\";";
  134 + }
  135 +
  136 + if ($_POST['To_Name'] != '') {
  137 + $mail->addAddress($to, $_POST['To_Name']);
  138 + $example_code .= "\n\$mail->addAddress(\"$to\", \"" . $_POST['To_Name'] . "\");";
  139 + } else {
  140 + $mail->addAddress($to);
  141 + $example_code .= "\n\$mail->addAddress(\"$to\");";
  142 + }
  143 +
  144 + if ($_POST['bcc_Email'] != '') {
  145 + $indiBCC = explode(" ", $_POST['bcc_Email']);
  146 + foreach ($indiBCC as $key => $value) {
  147 + $mail->addBCC($value);
  148 + $example_code .= "\n\$mail->addBCC(\"$value\");";
  149 + }
  150 + }
  151 +
  152 + if ($_POST['cc_Email'] != '') {
  153 + $indiCC = explode(" ", $_POST['cc_Email']);
  154 + foreach ($indiCC as $key => $value) {
  155 + $mail->addCC($value);
  156 + $example_code .= "\n\$mail->addCC(\"$value\");";
  157 + }
  158 + }
  159 + } catch (phpmailerException $e) { //Catch all kinds of bad addressing
  160 + throw new phpmailerAppException($e->getMessage());
  161 + }
  162 + $mail->Subject = $_POST['Subject'] . ' (PHPMailer test using ' . strtoupper($_POST['test_type']) . ')';
  163 + $example_code .= "\n\$mail->Subject = \"" . $_POST['Subject'] .
  164 + '(PHPMailer test using ' . strtoupper($_POST['test_type']) . ')";';
  165 +
  166 + if ($_POST['Message'] == '') {
  167 + $body = file_get_contents('contents.html');
  168 + } else {
  169 + $body = $_POST['Message'];
  170 + }
  171 +
  172 + $example_code .= "\n\$body = <<<'EOT'\n" . htmlentities($body) . "\nEOT;";
  173 +
  174 + $mail->WordWrap = 80; // set word wrap
  175 + $mail->msgHTML($body, dirname(__FILE__), true); //Create message bodies and embed images
  176 +
  177 + $example_code .= "\n\$mail->WordWrap = 80;";
  178 + $example_code .= "\n\$mail->msgHTML(\$body, dirname(__FILE__), true); //Create message bodies and embed images";
  179 +
  180 + $mail->addAttachment('images/phpmailer_mini.png', 'phpmailer_mini.png'); // optional name
  181 + $mail->addAttachment('images/phpmailer.png', 'phpmailer.png'); // optional name
  182 + $example_code .= "\n\$mail->addAttachment('images/phpmailer_mini.png'," .
  183 + "'phpmailer_mini.png'); // optional name";
  184 + $example_code .= "\n\$mail->addAttachment('images/phpmailer.png', 'phpmailer.png'); // optional name";
  185 +
  186 + try {
  187 + $mail->send();
  188 + $results_messages[] = "Message has been sent using " . strtoupper($_POST["test_type"]);
  189 + } catch (phpmailerException $e) {
  190 + throw new phpmailerAppException("Unable to send to: " . $to . ': ' . $e->getMessage());
  191 + }
  192 +
  193 + $example_code .= "\n\ntry {";
  194 + $example_code .= "\n \$mail->send();";
  195 + $example_code .= "\n \$results_messages[] = \"Message has been sent using " .
  196 + strtoupper($_POST['test_type']) . "\";";
  197 + $example_code .= "\n}";
  198 + $example_code .= "\ncatch (phpmailerException \$e) {";
  199 + $example_code .= "\n throw new phpmailerAppException('Unable to send to: ' . \$to. ': '.\$e->getMessage());";
  200 + $example_code .= "\n}";
  201 + }
  202 +} catch (phpmailerAppException $e) {
  203 + $results_messages[] = $e->errorMessage();
  204 +}
  205 +$example_code .= "\n}";
  206 +$example_code .= "\ncatch (phpmailerAppException \$e) {";
  207 +$example_code .= "\n \$results_messages[] = \$e->errorMessage();";
  208 +$example_code .= "\n}";
  209 +$example_code .= "\n\nif (count(\$results_messages) > 0) {";
  210 +$example_code .= "\n echo \"<h2>Run results</h2>\\n\";";
  211 +$example_code .= "\n echo \"<ul>\\n\";";
  212 +$example_code .= "\nforeach (\$results_messages as \$result) {";
  213 +$example_code .= "\n echo \"<li>\$result</li>\\n\";";
  214 +$example_code .= "\n}";
  215 +$example_code .= "\necho \"</ul>\\n\";";
  216 +$example_code .= "\n}";
  217 +?><!DOCTYPE html>
  218 +<html>
  219 +<head>
  220 + <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  221 + <title>PHPMailer Test Page</title>
  222 + <script type="text/javascript" src="scripts/shCore.js"></script>
  223 + <script type="text/javascript" src="scripts/shBrushPhp.js"></script>
  224 + <link type="text/css" rel="stylesheet" href="styles/shCore.css">
  225 + <link type="text/css" rel="stylesheet" href="styles/shThemeDefault.css">
  226 + <style>
  227 + body {
  228 + font-family: Arial, Helvetica, sans-serif;
  229 + font-size: 1em;
  230 + padding: 1em;
  231 + }
  232 +
  233 + table {
  234 + margin: 0 auto;
  235 + border-spacing: 0;
  236 + border-collapse: collapse;
  237 + }
  238 +
  239 + table.column {
  240 + border-collapse: collapse;
  241 + background-color: #FFFFFF;
  242 + padding: 0.5em;
  243 + width: 35em;
  244 + }
  245 +
  246 + td {
  247 + font-size: 1em;
  248 + padding: 0.1em 0.25em;
  249 + -moz-border-radius: 1em;
  250 + -webkit-border-radius: 1em;
  251 + border-radius: 1em;
  252 + }
  253 +
  254 + td.colleft {
  255 + text-align: right;
  256 + width: 35%;
  257 + }
  258 +
  259 + td.colrite {
  260 + text-align: left;
  261 + width: 65%;
  262 + }
  263 +
  264 + fieldset {
  265 + padding: 1em 1em 1em 1em;
  266 + margin: 0 2em;
  267 + border-radius: 1.5em;
  268 + -webkit-border-radius: 1em;
  269 + -moz-border-radius: 1em;
  270 + }
  271 +
  272 + fieldset.inner {
  273 + width: 40%;
  274 + }
  275 +
  276 + fieldset:hover, tr:hover {
  277 + background-color: #fafafa;
  278 + }
  279 +
  280 + legend {
  281 + font-weight: bold;
  282 + font-size: 1.1em;
  283 + }
  284 +
  285 + div.column-left {
  286 + float: left;
  287 + width: 45em;
  288 + height: 31em;
  289 + }
  290 +
  291 + div.column-right {
  292 + display: inline;
  293 + width: 45em;
  294 + max-height: 31em;
  295 + }
  296 +
  297 + input.radio {
  298 + float: left;
  299 + }
  300 +
  301 + div.radio {
  302 + padding: 0.2em;
  303 + }
  304 + </style>
  305 + <script>
  306 + SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
  307 + SyntaxHighlighter.all();
  308 +
  309 + function startAgain() {
  310 + var post_params = {
  311 + "From_Name": "<?php echo $from_name; ?>",
  312 + "From_Email": "<?php echo $from_email; ?>",
  313 + "To_Name": "<?php echo $to_name; ?>",
  314 + "To_Email": "<?php echo $to_email; ?>",
  315 + "cc_Email": "<?php echo $cc_email; ?>",
  316 + "bcc_Email": "<?php echo $bcc_email; ?>",
  317 + "Subject": "<?php echo $subject; ?>",
  318 + "Message": "<?php echo $message; ?>",
  319 + "test_type": "<?php echo $test_type; ?>",
  320 + "smtp_debug": "<?php echo $smtp_debug; ?>",
  321 + "smtp_server": "<?php echo $smtp_server; ?>",
  322 + "smtp_port": "<?php echo $smtp_port; ?>",
  323 + "smtp_secure": "<?php echo $smtp_secure; ?>",
  324 + "smtp_authenticate": "<?php echo $smtp_authenticate; ?>",
  325 + "authenticate_username": "<?php echo $authenticate_username; ?>",
  326 + "authenticate_password": "<?php echo $authenticate_password; ?>"
  327 + };
  328 +
  329 + var resetForm = document.createElement("form");
  330 + resetForm.setAttribute("method", "POST");
  331 + resetForm.setAttribute("path", "index.php");
  332 +
  333 + for (var k in post_params) {
  334 + var h = document.createElement("input");
  335 + h.setAttribute("type", "hidden");
  336 + h.setAttribute("name", k);
  337 + h.setAttribute("value", post_params[k]);
  338 + resetForm.appendChild(h);
  339 + }
  340 +
  341 + document.body.appendChild(resetForm);
  342 + resetForm.submit();
  343 + }
  344 +
  345 + function showHideDiv(test, element_id) {
  346 + var ops = {"smtp-options-table": "smtp"};
  347 +
  348 + if (test == ops[element_id]) {
  349 + document.getElementById(element_id).style.display = "block";
  350 + } else {
  351 + document.getElementById(element_id).style.display = "none";
  352 + }
  353 + }
  354 + </script>
  355 +</head>
  356 +<body>
  357 +<?php
  358 +if (version_compare(PHP_VERSION, '5.0.0', '<')) {
  359 + echo 'Current PHP version: ' . phpversion() . "<br>";
  360 + echo exit("ERROR: Wrong PHP version. Must be PHP 5 or above.");
  361 +}
  362 +
  363 +if (count($results_messages) > 0) {
  364 + echo '<h2>Run results</h2>';
  365 + echo '<ul>';
  366 + foreach ($results_messages as $result) {
  367 + echo "<li>$result</li>";
  368 + }
  369 + echo '</ul>';
  370 +}
  371 +
  372 +if (isset($_POST["submit"]) && $_POST["submit"] == "Submit") {
  373 + echo "<button type=\"submit\" onclick=\"startAgain();\">Start Over</button><br>\n";
  374 + echo "<br><span>Script:</span>\n";
  375 + echo "<pre class=\"brush: php;\">\n";
  376 + echo $example_code;
  377 + echo "\n</pre>\n";
  378 + echo "\n<hr style=\"margin: 3em;\">\n";
  379 +}
  380 +?>
  381 +<form method="POST" enctype="multipart/form-data">
  382 + <div>
  383 + <div class="column-left">
  384 + <fieldset>
  385 + <legend>Mail Details</legend>
  386 + <table border="1" class="column">
  387 + <tr>
  388 + <td class="colleft">
  389 + <label for="From_Name"><strong>From</strong> Name</label>
  390 + </td>
  391 + <td class="colrite">
  392 + <input type="text" id="From_Name" name="From_Name" value="<?php echo $from_name; ?>"
  393 + style="width:95%;" autofocus placeholder="Your Name">
  394 + </td>
  395 + </tr>
  396 + <tr>
  397 + <td class="colleft">
  398 + <label for="From_Email"><strong>From</strong> Email Address</label>
  399 + </td>
  400 + <td class="colrite">
  401 + <input type="text" id="From_Email" name="From_Email" value="<?php echo $from_email; ?>"
  402 + style="width:95%;" required placeholder="Your.Email@example.com">
  403 + </td>
  404 + </tr>
  405 + <tr>
  406 + <td class="colleft">
  407 + <label for="To_Name"><strong>To</strong> Name</label>
  408 + </td>
  409 + <td class="colrite">
  410 + <input type="text" id="To_Name" name="To_Name" value="<?php echo $to_name; ?>"
  411 + style="width:95%;" placeholder="Recipient's Name">
  412 + </td>
  413 + </tr>
  414 + <tr>
  415 + <td class="colleft">
  416 + <label for="To_Email"><strong>To</strong> Email Address</label>
  417 + </td>
  418 + <td class="colrite">
  419 + <input type="text" id="To_Email" name="To_Email" value="<?php echo $to_email; ?>"
  420 + style="width:95%;" required placeholder="Recipients.Email@example.com">
  421 + </td>
  422 + </tr>
  423 + <tr>
  424 + <td class="colleft">
  425 + <label for="cc_Email"><strong>CC Recipients</strong><br>
  426 + <small>(separate with commas)</small>
  427 + </label>
  428 + </td>
  429 + <td class="colrite">
  430 + <input type="text" id="cc_Email" name="cc_Email" value="<?php echo $cc_email; ?>"
  431 + style="width:95%;" placeholder="cc1@example.com, cc2@example.com">
  432 + </td>
  433 + </tr>
  434 + <tr>
  435 + <td class="colleft">
  436 + <label for="bcc_Email"><strong>BCC Recipients</strong><br>
  437 + <small>(separate with commas)</small>
  438 + </label>
  439 + </td>
  440 + <td class="colrite">
  441 + <input type="text" id="bcc_Email" name="bcc_Email" value="<?php echo $bcc_email; ?>"
  442 + style="width:95%;" placeholder="bcc1@example.com, bcc2@example.com">
  443 + </td>
  444 + </tr>
  445 + <tr>
  446 + <td class="colleft">
  447 + <label for="Subject"><strong>Subject</strong></label>
  448 + </td>
  449 + <td class="colrite">
  450 + <input type="text" name="Subject" id="Subject" value="<?php echo $subject; ?>"
  451 + style="width:95%;" placeholder="Email Subject">
  452 + </td>
  453 + </tr>
  454 + <tr>
  455 + <td class="colleft">
  456 + <label for="Message"><strong>Message</strong><br>
  457 + <small>If blank, will use content.html</small>
  458 + </label>
  459 + </td>
  460 + <td class="colrite">
  461 + <textarea name="Message" id="Message" style="width:95%;height:5em;"
  462 + placeholder="Body of your email"><?php echo $message; ?></textarea>
  463 + </td>
  464 + </tr>
  465 + </table>
  466 + <div style="margin:1em 0;">Test will include two attachments.</div>
  467 + </fieldset>
  468 + </div>
  469 + <div class="column-right">
  470 + <fieldset class="inner"> <!-- SELECT TYPE OF MAIL -->
  471 + <legend>Mail Test Specs</legend>
  472 + <table border="1" class="column">
  473 + <tr>
  474 + <td class="colleft">Test Type</td>
  475 + <td class="colrite">
  476 + <div class="radio">
  477 + <label for="radio-mail">Mail()</label>
  478 + <input class="radio" type="radio" name="test_type" value="mail" id="radio-mail"
  479 + onclick="showHideDiv(this.value, 'smtp-options-table');"
  480 + <?php echo ($test_type == 'mail') ? 'checked' : ''; ?>
  481 + required>
  482 + </div>
  483 + <div class="radio">
  484 + <label for="radio-sendmail">Sendmail</label>
  485 + <input class="radio" type="radio" name="test_type" value="sendmail" id="radio-sendmail"
  486 + onclick="showHideDiv(this.value, 'smtp-options-table');"
  487 + <?php echo ($test_type == 'sendmail') ? 'checked' : ''; ?>
  488 + required>
  489 + </div>
  490 + <div class="radio">
  491 + <label for="radio-qmail">Qmail</label>
  492 + <input class="radio" type="radio" name="test_type" value="qmail" id="radio-qmail"
  493 + onclick="showHideDiv(this.value, 'smtp-options-table');"
  494 + <?php echo ($test_type == 'qmail') ? 'checked' : ''; ?>
  495 + required>
  496 + </div>
  497 + <div class="radio">
  498 + <label for="radio-smtp">SMTP</label>
  499 + <input class="radio" type="radio" name="test_type" value="smtp" id="radio-smtp"
  500 + onclick="showHideDiv(this.value, 'smtp-options-table');"
  501 + <?php echo ($test_type == 'smtp') ? 'checked' : ''; ?>
  502 + required>
  503 + </div>
  504 + </td>
  505 + </tr>
  506 + </table>
  507 + <div id="smtp-options-table" style="margin:1em 0 0 0;
  508 +<?php if ($test_type != 'smtp') {
  509 + echo "display: none;";
  510 +} ?>">
  511 + <span style="margin:1.25em 0; display:block;"><strong>SMTP Specific Options:</strong></span>
  512 + <table border="1" class="column">
  513 + <tr>
  514 + <td class="colleft"><label for="smtp_debug">SMTP Debug ?</label></td>
  515 + <td class="colrite">
  516 + <select size="1" id="smtp_debug" name="smtp_debug">
  517 + <option <?php echo ($smtp_debug == '0') ? 'selected' : ''; ?> value="0">
  518 + 0 - Disabled
  519 + </option>
  520 + <option <?php echo ($smtp_debug == '1') ? 'selected' : ''; ?> value="1">
  521 + 1 - Client messages
  522 + </option>
  523 + <option <?php echo ($smtp_debug == '2') ? 'selected' : ''; ?> value="2">
  524 + 2 - Client and server messages
  525 + </option>
  526 + </select>
  527 + </td>
  528 + </tr>
  529 + <tr>
  530 + <td class="colleft"><label for="smtp_server">SMTP Server</label></td>
  531 + <td class="colrite">
  532 + <input type="text" id="smtp_server" name="smtp_server"
  533 + value="<?php echo $smtp_server; ?>" style="width:95%;"
  534 + placeholder="smtp.server.com">
  535 + </td>
  536 + </tr>
  537 + <tr>
  538 + <td class="colleft" style="width: 5em;"><label for="smtp_port">SMTP Port</label></td>
  539 + <td class="colrite">
  540 + <input type="text" name="smtp_port" id="smtp_port" size="3"
  541 + value="<?php echo $smtp_port; ?>" placeholder="Port">
  542 + </td>
  543 + </tr>
  544 + <tr>
  545 + <td class="colleft"><label for="smtp_secure">SMTP Security</label></td>
  546 + <td>
  547 + <select size="1" name="smtp_secure" id="smtp_secure">
  548 + <option <?php echo ($smtp_secure == 'none') ? 'selected' : '' ?>>None</option>
  549 + <option <?php echo ($smtp_secure == 'tls') ? 'selected' : '' ?>>TLS</option>
  550 + <option <?php echo ($smtp_secure == 'ssl') ? 'selected' : '' ?>>SSL</option>
  551 + </select>
  552 + </td>
  553 + </tr>
  554 + <tr>
  555 + <td class="colleft"><label for="smtp-authenticate">SMTP Authenticate?</label></td>
  556 + <td class="colrite">
  557 + <input type="checkbox" id="smtp-authenticate"
  558 + name="smtp_authenticate"
  559 +<?php if ($smtp_authenticate != '') {
  560 + echo "checked";
  561 +} ?>
  562 + value="<?php echo $smtp_authenticate; ?>">
  563 + </td>
  564 + </tr>
  565 + <tr>
  566 + <td class="colleft"><label for="authenticate_username">Authenticate Username</label></td>
  567 + <td class="colrite">
  568 + <input type="text" id="authenticate_username" name="authenticate_username"
  569 + value="<?php echo $authenticate_username; ?>" style="width:95%;"
  570 + placeholder="SMTP Server Username">
  571 + </td>
  572 + </tr>
  573 + <tr>
  574 + <td class="colleft"><label for="authenticate_password">Authenticate Password</label></td>
  575 + <td class="colrite">
  576 + <input type="password" name="authenticate_password" id="authenticate_password"
  577 + value="<?php echo $authenticate_password; ?>" style="width:95%;"
  578 + placeholder="SMTP Server Password">
  579 + </td>
  580 + </tr>
  581 + </table>
  582 + </div>
  583 + </fieldset>
  584 + </div>
  585 + <br style="clear:both;">
  586 +
  587 + <div style="margin-left:2em; margin-bottom:5em; float:left;">
  588 + <div style="margin-bottom: 1em; ">
  589 + <input type="submit" value="Submit" name="submit">
  590 + </div>
  591 + <?php echo 'Current PHP version: ' . phpversion(); ?>
  592 + </div>
  593 + </div>
  594 +</form>
  595 +</body>
  596 +</html>
\ No newline at end of file
... ...
  1 +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2 +<html>
  3 +<head>
  4 + <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5 + <title>PHPMailer Test</title>
  6 +</head>
  7 +<body>
  8 + <div style="width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 11px;">
  9 + <h1>This is a test of PHPMailer.</h1>
  10 + <div align="center">
  11 + <a href="https://github.com/PHPMailer/PHPMailer/"><img src="images/phpmailer.png" height="90" width="340" alt="PHPMailer rocks"></a>
  12 + </div>
  13 + <p>This example uses <strong>HTML</strong>.</p>
  14 + <p>The PHPMailer image at the top has been embedded automatically.</p>
  15 + </div>
  16 +</body>
  17 +</html>
... ...
  1 +<!DOCTYPE html>
  2 +<html>
  3 +<head>
  4 + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  5 + <title>PHPMailer - Exceptions test</title>
  6 +</head>
  7 +<body>
  8 +<?php
  9 +require '../PHPMailerAutoload.php';
  10 +
  11 +//Create a new PHPMailer instance
  12 +//Passing true to the constructor enables the use of exceptions for error handling
  13 +$mail = new PHPMailer(true);
  14 +try {
  15 + //Set who the message is to be sent from
  16 + $mail->setFrom('from@example.com', 'First Last');
  17 + //Set an alternative reply-to address
  18 + $mail->addReplyTo('replyto@example.com', 'First Last');
  19 + //Set who the message is to be sent to
  20 + $mail->addAddress('whoto@example.com', 'John Doe');
  21 + //Set the subject line
  22 + $mail->Subject = 'PHPMailer Exceptions test';
  23 + //Read an HTML message body from an external file, convert referenced images to embedded,
  24 + //and convert the HTML into a basic plain-text alternative body
  25 + $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
  26 + //Replace the plain text body with one created manually
  27 + $mail->AltBody = 'This is a plain-text message body';
  28 + //Attach an image file
  29 + $mail->addAttachment('images/phpmailer_mini.png');
  30 + //send the message
  31 + //Note that we don't need check the response from this because it will throw an exception if it has trouble
  32 + $mail->send();
  33 + echo "Message sent!";
  34 +} catch (phpmailerException $e) {
  35 + echo $e->errorMessage(); //Pretty error messages from PHPMailer
  36 +} catch (Exception $e) {
  37 + echo $e->getMessage(); //Boring error messages from anything else!
  38 +}
  39 +?>
  40 +</body>
  41 +</html>
... ...
  1 +<!DOCTYPE html>
  2 +<html>
  3 +<head>
  4 + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  5 + <title>PHPMailer - GMail SMTP test</title>
  6 +</head>
  7 +<body>
  8 +<?php
  9 +
  10 +//SMTP needs accurate times, and the PHP time zone MUST be set
  11 +//This should be done in your php.ini, but this is how to do it if you don't have access to that
  12 +date_default_timezone_set('Etc/UTC');
  13 +
  14 +require '../PHPMailerAutoload.php';
  15 +
  16 +//Create a new PHPMailer instance
  17 +$mail = new PHPMailer();
  18 +
  19 +//Tell PHPMailer to use SMTP
  20 +$mail->isSMTP();
  21 +
  22 +//Enable SMTP debugging
  23 +// 0 = off (for production use)
  24 +// 1 = client messages
  25 +// 2 = client and server messages
  26 +$mail->SMTPDebug = 2;
  27 +
  28 +//Ask for HTML-friendly debug output
  29 +$mail->Debugoutput = 'html';
  30 +
  31 +//Set the hostname of the mail server
  32 +$mail->Host = 'smtp.gmail.com';
  33 +
  34 +//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
  35 +$mail->Port = 587;
  36 +
  37 +//Set the encryption system to use - ssl (deprecated) or tls
  38 +$mail->SMTPSecure = 'tls';
  39 +
  40 +//Whether to use SMTP authentication
  41 +$mail->SMTPAuth = true;
  42 +
  43 +//Username to use for SMTP authentication - use full email address for gmail
  44 +$mail->Username = "username@gmail.com";
  45 +
  46 +//Password to use for SMTP authentication
  47 +$mail->Password = "yourpassword";
  48 +
  49 +//Set who the message is to be sent from
  50 +$mail->setFrom('from@example.com', 'First Last');
  51 +
  52 +//Set an alternative reply-to address
  53 +$mail->addReplyTo('replyto@example.com', 'First Last');
  54 +
  55 +//Set who the message is to be sent to
  56 +$mail->addAddress('whoto@example.com', 'John Doe');
  57 +
  58 +//Set the subject line
  59 +$mail->Subject = 'PHPMailer GMail SMTP test';
  60 +
  61 +//Read an HTML message body from an external file, convert referenced images to embedded,
  62 +//convert HTML into a basic plain-text alternative body
  63 +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
  64 +
  65 +//Replace the plain text body with one created manually
  66 +$mail->AltBody = 'This is a plain-text message body';
  67 +
  68 +//Attach an image file
  69 +$mail->addAttachment('images/phpmailer_mini.png');
  70 +
  71 +//send the message, check for errors
  72 +if (!$mail->send()) {
  73 + echo "Mailer Error: " . $mail->ErrorInfo;
  74 +} else {
  75 + echo "Message sent!";
  76 +}
  77 +?>
  78 +</body>
  79 +</html>
... ...
  1 +<!DOCTYPE html>
  2 +<html>
  3 +<head>
  4 + <meta charset="UTF-8">
  5 + <title>PHPMailer Examples</title>
  6 +</head>
  7 +<body>
  8 +<h1>PHPMailer code examples<a href="https://github.com/PHPMailer/PHPMailer"><img src="images/phpmailer.png" style="float:right; border:0;" alt="PHPMailer logo"></a></h1>
  9 +<p>This folder contains a collection of examples of using <a href="https://github.com/PHPMailer/PHPMailer">PHPMailer</a>.</p>
  10 +<h2>About testing email sending</h2>
  11 +<p>When working on email sending code you'll find yourself worrying about what might happen if all these test emails got sent to your mailing list. The solution is to use a fake mail server, one that acts just like the real thing, but just doesn't actually send anything out. Some offer web interfaces, feedback, logging, the ability to return specific error codes, all things that are useful for testing error handling, authentication etc. Here's a selection of mail testing tools you might like to try:</p>
  12 +<ul>
  13 + <li><a href="https://github.com/isotoma/FakeEmail">FakeEmail</a>, a Python-based fake mail server with a web interface.</li>
  14 + <li><a href="http://www.postfix.org/smtp-sink.1.html">smtp-sink</a>, part of the Postfix mail server, so you probably already have this installed. This is used in the Travis-CI configuration to run PHPMailer's unit tests.</li>
  15 + <li><a href="https://github.com/Nilhcem/FakeSMTP">FakeSMTP</a>, a Java desktop app with the ability to show an SMTP log and save messages to a folder.</li>
  16 + <li><a href="http://smtp4dev.codeplex.com">smtp4dev</a>, a dummy SMTP server for Windows.</li>
  17 + <li><a href="https://github.com/PHPMailer/PHPMailer/blob/master/test/fakesendmail.sh">fakesendmail.sh</a>, part of PHPMailer's test setup, this is a shell script that emulates sendmail for testing 'mail' or 'sendmail' methods in PHPMailer.</li>
  18 + <li><a href="http://tools.ietf.org/tools/msglint/">msglint</a>, not a mail server, the IETF's MIME structure analyser checks the formatting of your messages.</li>
  19 +</ul>
  20 +<div style="padding: 8px; color: #333333; background-color: #dc8b92">
  21 +<h2>Security note</h2>
  22 +<p>Before running these examples you'll need to rename them with '.php' extensions. They are supplied as '.phps' files which will usually be displayed with syntax highlighting by PHP instead of running them. This prevents potential security issues with running potential spam-gateway code if you happen to deploy these code examples on a live site - <em>please don't do that!</em> Similarly, don't leave your passwords in these files as they will be visible to the world!</p>
  23 +</div>
  24 +<h2><a href="code_generator.phps">code_generator.phps</a></h2>
  25 +<p>This script is a simple code generator - fill in the form and hit submit, and it will use when you entered to email you a message, and will also generate PHP code using your settings that you can copy and paste to use in your own apps. If you need to get going quickly, this is probably the best place to start.</p>
  26 +<h2><a href="mail.phps">mail.phps</a></h2>
  27 +<p>This script is a basic example which creates an email message from an external HTML file, creates a plain text body, sets various addresses, adds an attachment and sends the message. It uses PHP's built-in mail() function which is the simplest to use, but relies on the presence of a local mail server, something which is not usually available on Windows. If you find yourself in that sitution, either install a local mail server, or use a remote one and send using SMTP instead.</p>
  28 +<h2><a href="exceptions.phps">exceptions.phps</a></h2>
  29 +<p>The same as the mail example, but shows how to use PHPMailer's optional exceptions for error handling.</p>
  30 +<h2><a href="smtp.phps">smtp.phps</a></h2>
  31 +<p>A simple example sending using SMTP with authentication.</p>
  32 +<h2><a href="smtp_no_auth.phps">smtp_no_auth.phps</a></h2>
  33 +<p>A simple example sending using SMTP without authentication.</p>
  34 +<h2><a href="sendmail.phps">sendmail.phps</a></h2>
  35 +<p>A simple example using sendmail. Sendmail is a program (usually found on Linux/BSD, OS X and other UNIX-alikes) that can be used to submit messages to a local mail server without a lengthy SMTP conversation. It's probably the fastest sending mechanism, but lacks some error reporting features. There are sendmail emulators for most popular mail servers including postfix, qmail, exim etc.</p>
  36 +<h2><a href="gmail.phps">gmail.phps</a></h2>
  37 +<p>Submitting email via Google's Gmail service is a popular use of PHPMailer. It's much the same as normal SMTP sending, just with some specific settings, namely using TLS encryption, authentication is enabled, and it connects to the SMTP submission port 587 on the smtp.gmail.com host. This example does all that.</p>
  38 +<h2><a href="pop_before_smtp.phps">pop_before_smtp.phps</a></h2>
  39 +<p>Before effective SMTP authentication mechanisms were available, it was common for ISPs to use POP-before-SMTP authentication. As it implies, you authenticate using the POP3 protocol (an older protocol now mostly replaced by the far superior IMAP), and then the SMTP server will allow send access from your IP address for a short while, usually 5-15 minutes. PHPMailer includes a POP3 protocol client, so it can carry out this sequence - it's just like a normal SMTP conversation (without authentication), but connects via POP first.</p>
  40 +<h2><a href="mailing_list.phps">mailing_list.phps</a></h2>
  41 +<p>This is a somewhat naïve example of sending similar emails to a list of different addresses. It sets up a PHPMailer instance using SMTP, then connects to a MySQL database to retrieve a list of recipients. The code loops over this list, sending email to each person using their info and marks them as sent in the database. It makes use of SMTP keepalive which saves reconnecting and re-authenticating between each message.</p>
  42 +<hr>
  43 +<p>Most of these examples use the 'example.com' domain. This domain is reserved by IANA for illustrative purposes, as documented in <a href="http://tools.ietf.org/html/rfc2606">RFC 2606</a>. Don't use made-up domains like 'mydomain.com' or 'somedomain.com' in examples as someone, somewhere, probably owns them!</p>
  44 +</body>
  45 +</html>
... ...
  1 +<!DOCTYPE html>
  2 +<html>
  3 +<head>
  4 + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  5 + <title>PHPMailer - mail() test</title>
  6 +</head>
  7 +<body>
  8 +<?php
  9 +require '../PHPMailerAutoload.php';
  10 +
  11 +//Create a new PHPMailer instance
  12 +$mail = new PHPMailer();
  13 +//Set who the message is to be sent from
  14 +$mail->setFrom('from@example.com', 'First Last');
  15 +//Set an alternative reply-to address
  16 +$mail->addReplyTo('replyto@example.com', 'First Last');
  17 +//Set who the message is to be sent to
  18 +$mail->addAddress('whoto@example.com', 'John Doe');
  19 +//Set the subject line
  20 +$mail->Subject = 'PHPMailer mail() test';
  21 +//Read an HTML message body from an external file, convert referenced images to embedded,
  22 +//convert HTML into a basic plain-text alternative body
  23 +$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
  24 +//Replace the plain text body with one created manually
  25 +$mail->AltBody = 'This is a plain-text message body';
  26 +//Attach an image file
  27 +$mail->addAttachment('images/phpmailer_mini.png');
  28 +
  29 +//send the message, check for errors
  30 +if (!$mail->send()) {
  31 + echo "Mailer Error: " . $mail->ErrorInfo;
  32 +} else {
  33 + echo "Message sent!";
  34 +}
  35 +?>
  36 +</body>
  37 +</html>
... ...
  1 +<?php
  2 +
  3 +error_reporting(E_STRICT | E_ALL);
  4 +
  5 +date_default_timezone_set('Etc/UTC');
  6 +
  7 +require '../PHPMailerAutoload.php';
  8 +
  9 +$mail = new PHPMailer();
  10 +
  11 +$body = file_get_contents('contents.html');
  12 +
  13 +$mail->isSMTP();
  14 +$mail->Host = 'smtp.example.com';
  15 +$mail->SMTPAuth = true;
  16 +$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
  17 +$mail->Port = 25;
  18 +$mail->Username = 'yourname@example.com';
  19 +$mail->Password = 'yourpassword';
  20 +$mail->setFrom('list@example.com', 'List manager');
  21 +$mail->addReplyTo('list@example.com', 'List manager');
  22 +
  23 +$mail->Subject = "PHPMailer Simple database mailing list test";
  24 +
  25 +//Same body for all messages, so set this before the sending loop
  26 +//If you generate a different body for each recipient (e.g. you're using a templating system),
  27 +//set it inside the loop
  28 +$mail->msgHTML($body);
  29 +//msgHTML also sets AltBody, so if you want a custom one, set it afterwards
  30 +$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
  31 +
  32 +//Connect to the database and select the recipients from your mailing list that have not yet been sent to
  33 +//You'll need to alter this to match your database
  34 +$mysql = mysql_connect('localhost', 'username', 'password');
  35 +mysql_select_db('mydb', $mysql);
  36 +$result = mysql_query("SELECT full_name, email, photo FROM mailinglist WHERE sent = false", $mysql);
  37 +
  38 +while ($row = mysql_fetch_array($result)) {
  39 + $mail->addAddress($row['email'], $row['full_name']);
  40 + $mail->addStringAttachment($row['photo'], 'YourPhoto.jpg'); //Assumes the image data is stored in the DB
  41 +
  42 + if (!$mail->send()) {
  43 + echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
  44 + break; //Abandon sending
  45 + } else {
  46 + echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("@", "&#64;", $row['email']) . ')<br />';
  47 + //Mark it as sent in the DB
  48 + mysql_query(
  49 + "UPDATE mailinglist SET sent = true WHERE email = '" . mysql_real_escape_string($row['email'], $mysql) . "'"
  50 + );
  51 + }
  52 + // Clear all addresses and attachments for next loop
  53 + $mail->clearAddresses();
  54 + $mail->clearAttachments();
  55 +}
... ...
  1 +<!DOCTYPE html>
  2 +<html>
  3 +<head>
  4 + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  5 + <title>PHPMailer - POP-before-SMTP test</title>
  6 +</head>
  7 +<body>
  8 +<?php
  9 +require '../PHPMailerAutoload.php';
  10 +
  11 +//Authenticate via POP3
  12 +//Now you should be clear to submit messages over SMTP for a while
  13 +//Only applies if your host supports POP-before-SMTP
  14 +$pop = POP3::popBeforeSmtp('pop3.example.com', 110, 30, 'username', 'password', 1);
  15 +
  16 +//Create a new PHPMailer instance
  17 +//Passing true to the constructor enables the use of exceptions for error handling
  18 +$mail = new PHPMailer(true);
  19 +try {
  20 + $mail->isSMTP();
  21 + //Enable SMTP debugging
  22 + // 0 = off (for production use)
  23 + // 1 = client messages
  24 + // 2 = client and server messages
  25 + $mail->SMTPDebug = 2;
  26 + //Ask for HTML-friendly debug output
  27 + $mail->Debugoutput = 'html';
  28 + //Set the hostname of the mail server
  29 + $mail->Host = "mail.example.com";
  30 + //Set the SMTP port number - likely to be 25, 465 or 587
  31 + $mail->Port = 25;
  32 + //Whether to use SMTP authentication
  33 + $mail->SMTPAuth = false;
  34 + //Set who the message is to be sent from
  35 + $mail->setFrom('from@example.com', 'First Last');
  36 + //Set an alternative reply-to address
  37 + $mail->addReplyTo('replyto@example.com', 'First Last');
  38 + //Set who the message is to be sent to
  39 + $mail->addAddress('whoto@example.com', 'John Doe');
  40 + //Set the subject line
  41 + $mail->Subject = 'PHPMailer POP-before-SMTP test';
  42 + //Read an HTML message body from an external file, convert referenced images to embedded,
  43 + //and convert the HTML into a basic plain-text alternative body
  44 + $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
  45 + //Replace the plain text body with one created manually
  46 + $mail->AltBody = 'This is a plain-text message body';
  47 + //Attach an image file
  48 + $mail->addAttachment('images/phpmailer_mini.png');
  49 + //send the message
  50 + //Note that we don't need check the response from this because it will throw an exception if it has trouble
  51 + $mail->send();
  52 + echo "Message sent!";
  53 +} catch (phpmailerException $e) {
  54 + echo $e->errorMessage(); //Pretty error messages from PHPMailer
  55 +} catch (Exception $e) {
  56 + echo $e->getMessage(); //Boring error messages from anything else!
  57 +}
  58 +?>
  59 +</body>
  60 +</html>
... ...
  1 +// XRegExp 1.5.1
  2 +// (c) 2007-2012 Steven Levithan
  3 +// MIT License
  4 +// <http://xregexp.com>
  5 +// Provides an augmented, extensible, cross-browser implementation of regular expressions,
  6 +// including support for additional syntax, flags, and methods
  7 +
  8 +var XRegExp;
  9 +
  10 +if (XRegExp) {
  11 + // Avoid running twice, since that would break references to native globals
  12 + throw Error("can't load XRegExp twice in the same frame");
  13 +}
  14 +
  15 +// Run within an anonymous function to protect variables and avoid new globals
  16 +(function (undefined) {
  17 +
  18 + //---------------------------------
  19 + // Constructor
  20 + //---------------------------------
  21 +
  22 + // Accepts a pattern and flags; returns a new, extended `RegExp` object. Differs from a native
  23 + // regular expression in that additional syntax and flags are supported and cross-browser
  24 + // syntax inconsistencies are ameliorated. `XRegExp(/regex/)` clones an existing regex and
  25 + // converts to type XRegExp
  26 + XRegExp = function (pattern, flags) {
  27 + var output = [],
  28 + currScope = XRegExp.OUTSIDE_CLASS,
  29 + pos = 0,
  30 + context, tokenResult, match, chr, regex;
  31 +
  32 + if (XRegExp.isRegExp(pattern)) {
  33 + if (flags !== undefined)
  34 + throw TypeError("can't supply flags when constructing one RegExp from another");
  35 + return clone(pattern);
  36 + }
  37 + // Tokens become part of the regex construction process, so protect against infinite
  38 + // recursion when an XRegExp is constructed within a token handler or trigger
  39 + if (isInsideConstructor)
  40 + throw Error("can't call the XRegExp constructor within token definition functions");
  41 +
  42 + flags = flags || "";
  43 + context = { // `this` object for custom tokens
  44 + hasNamedCapture: false,
  45 + captureNames: [],
  46 + hasFlag: function (flag) {return flags.indexOf(flag) > -1;},
  47 + setFlag: function (flag) {flags += flag;}
  48 + };
  49 +
  50 + while (pos < pattern.length) {
  51 + // Check for custom tokens at the current position
  52 + tokenResult = runTokens(pattern, pos, currScope, context);
  53 +
  54 + if (tokenResult) {
  55 + output.push(tokenResult.output);
  56 + pos += (tokenResult.match[0].length || 1);
  57 + } else {
  58 + // Check for native multicharacter metasequences (excluding character classes) at
  59 + // the current position
  60 + if (match = nativ.exec.call(nativeTokens[currScope], pattern.slice(pos))) {
  61 + output.push(match[0]);
  62 + pos += match[0].length;
  63 + } else {
  64 + chr = pattern.charAt(pos);
  65 + if (chr === "[")
  66 + currScope = XRegExp.INSIDE_CLASS;
  67 + else if (chr === "]")
  68 + currScope = XRegExp.OUTSIDE_CLASS;
  69 + // Advance position one character
  70 + output.push(chr);
  71 + pos++;
  72 + }
  73 + }
  74 + }
  75 +
  76 + regex = RegExp(output.join(""), nativ.replace.call(flags, flagClip, ""));
  77 + regex._xregexp = {
  78 + source: pattern,
  79 + captureNames: context.hasNamedCapture ? context.captureNames : null
  80 + };
  81 + return regex;
  82 + };
  83 +
  84 +
  85 + //---------------------------------
  86 + // Public properties
  87 + //---------------------------------
  88 +
  89 + XRegExp.version = "1.5.1";
  90 +
  91 + // Token scope bitflags
  92 + XRegExp.INSIDE_CLASS = 1;
  93 + XRegExp.OUTSIDE_CLASS = 2;
  94 +
  95 +
  96 + //---------------------------------
  97 + // Private variables
  98 + //---------------------------------
  99 +
  100 + var replacementToken = /\$(?:(\d\d?|[$&`'])|{([$\w]+)})/g,
  101 + flagClip = /[^gimy]+|([\s\S])(?=[\s\S]*\1)/g, // Nonnative and duplicate flags
  102 + quantifier = /^(?:[?*+]|{\d+(?:,\d*)?})\??/,
  103 + isInsideConstructor = false,
  104 + tokens = [],
  105 + // Copy native globals for reference ("native" is an ES3 reserved keyword)
  106 + nativ = {
  107 + exec: RegExp.prototype.exec,
  108 + test: RegExp.prototype.test,
  109 + match: String.prototype.match,
  110 + replace: String.prototype.replace,
  111 + split: String.prototype.split
  112 + },
  113 + compliantExecNpcg = nativ.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups
  114 + compliantLastIndexIncrement = function () {
  115 + var x = /^/g;
  116 + nativ.test.call(x, "");
  117 + return !x.lastIndex;
  118 + }(),
  119 + hasNativeY = RegExp.prototype.sticky !== undefined,
  120 + nativeTokens = {};
  121 +
  122 + // `nativeTokens` match native multicharacter metasequences only (including deprecated octals,
  123 + // excluding character classes)
  124 + nativeTokens[XRegExp.INSIDE_CLASS] = /^(?:\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S]))/;
  125 + nativeTokens[XRegExp.OUTSIDE_CLASS] = /^(?:\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\d*|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S])|\(\?[:=!]|[?*+]\?|{\d+(?:,\d*)?}\??)/;
  126 +
  127 +
  128 + //---------------------------------
  129 + // Public methods
  130 + //---------------------------------
  131 +
  132 + // Lets you extend or change XRegExp syntax and create custom flags. This is used internally by
  133 + // the XRegExp library and can be used to create XRegExp plugins. This function is intended for
  134 + // users with advanced knowledge of JavaScript's regular expression syntax and behavior. It can
  135 + // be disabled by `XRegExp.freezeTokens`
  136 + XRegExp.addToken = function (regex, handler, scope, trigger) {
  137 + tokens.push({
  138 + pattern: clone(regex, "g" + (hasNativeY ? "y" : "")),
  139 + handler: handler,
  140 + scope: scope || XRegExp.OUTSIDE_CLASS,
  141 + trigger: trigger || null
  142 + });
  143 + };
  144 +
  145 + // Accepts a pattern and flags; returns an extended `RegExp` object. If the pattern and flag
  146 + // combination has previously been cached, the cached copy is returned; otherwise the newly
  147 + // created regex is cached
  148 + XRegExp.cache = function (pattern, flags) {
  149 + var key = pattern + "/" + (flags || "");
  150 + return XRegExp.cache[key] || (XRegExp.cache[key] = XRegExp(pattern, flags));
  151 + };
  152 +
  153 + // Accepts a `RegExp` instance; returns a copy with the `/g` flag set. The copy has a fresh
  154 + // `lastIndex` (set to zero). If you want to copy a regex without forcing the `global`
  155 + // property, use `XRegExp(regex)`. Do not use `RegExp(regex)` because it will not preserve
  156 + // special properties required for named capture
  157 + XRegExp.copyAsGlobal = function (regex) {
  158 + return clone(regex, "g");
  159 + };
  160 +
  161 + // Accepts a string; returns the string with regex metacharacters escaped. The returned string
  162 + // can safely be used at any point within a regex to match the provided literal string. Escaped
  163 + // characters are [ ] { } ( ) * + ? - . , \ ^ $ | # and whitespace
  164 + XRegExp.escape = function (str) {
  165 + return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  166 + };
  167 +
  168 + // Accepts a string to search, regex to search with, position to start the search within the
  169 + // string (default: 0), and an optional Boolean indicating whether matches must start at-or-
  170 + // after the position or at the specified position only. This function ignores the `lastIndex`
  171 + // of the provided regex in its own handling, but updates the property for compatibility
  172 + XRegExp.execAt = function (str, regex, pos, anchored) {
  173 + var r2 = clone(regex, "g" + ((anchored && hasNativeY) ? "y" : "")),
  174 + match;
  175 + r2.lastIndex = pos = pos || 0;
  176 + match = r2.exec(str); // Run the altered `exec` (required for `lastIndex` fix, etc.)
  177 + if (anchored && match && match.index !== pos)
  178 + match = null;
  179 + if (regex.global)
  180 + regex.lastIndex = match ? r2.lastIndex : 0;
  181 + return match;
  182 + };
  183 +
  184 + // Breaks the unrestorable link to XRegExp's private list of tokens, thereby preventing
  185 + // syntax and flag changes. Should be run after XRegExp and any plugins are loaded
  186 + XRegExp.freezeTokens = function () {
  187 + XRegExp.addToken = function () {
  188 + throw Error("can't run addToken after freezeTokens");
  189 + };
  190 + };
  191 +
  192 + // Accepts any value; returns a Boolean indicating whether the argument is a `RegExp` object.
  193 + // Note that this is also `true` for regex literals and regexes created by the `XRegExp`
  194 + // constructor. This works correctly for variables created in another frame, when `instanceof`
  195 + // and `constructor` checks would fail to work as intended
  196 + XRegExp.isRegExp = function (o) {
  197 + return Object.prototype.toString.call(o) === "[object RegExp]";
  198 + };
  199 +
  200 + // Executes `callback` once per match within `str`. Provides a simpler and cleaner way to
  201 + // iterate over regex matches compared to the traditional approaches of subverting
  202 + // `String.prototype.replace` or repeatedly calling `exec` within a `while` loop
  203 + XRegExp.iterate = function (str, regex, callback, context) {
  204 + var r2 = clone(regex, "g"),
  205 + i = -1, match;
  206 + while (match = r2.exec(str)) { // Run the altered `exec` (required for `lastIndex` fix, etc.)
  207 + if (regex.global)
  208 + regex.lastIndex = r2.lastIndex; // Doing this to follow expectations if `lastIndex` is checked within `callback`
  209 + callback.call(context, match, ++i, str, regex);
  210 + if (r2.lastIndex === match.index)
  211 + r2.lastIndex++;
  212 + }
  213 + if (regex.global)
  214 + regex.lastIndex = 0;
  215 + };
  216 +
  217 + // Accepts a string and an array of regexes; returns the result of using each successive regex
  218 + // to search within the matches of the previous regex. The array of regexes can also contain
  219 + // objects with `regex` and `backref` properties, in which case the named or numbered back-
  220 + // references specified are passed forward to the next regex or returned. E.g.:
  221 + // var xregexpImgFileNames = XRegExp.matchChain(html, [
  222 + // {regex: /<img\b([^>]+)>/i, backref: 1}, // <img> tag attributes
  223 + // {regex: XRegExp('(?ix) \\s src=" (?<src> [^"]+ )'), backref: "src"}, // src attribute values
  224 + // {regex: XRegExp("^http://xregexp\\.com(/[^#?]+)", "i"), backref: 1}, // xregexp.com paths
  225 + // /[^\/]+$/ // filenames (strip directory paths)
  226 + // ]);
  227 + XRegExp.matchChain = function (str, chain) {
  228 + return function recurseChain (values, level) {
  229 + var item = chain[level].regex ? chain[level] : {regex: chain[level]},
  230 + regex = clone(item.regex, "g"),
  231 + matches = [], i;
  232 + for (i = 0; i < values.length; i++) {
  233 + XRegExp.iterate(values[i], regex, function (match) {
  234 + matches.push(item.backref ? (match[item.backref] || "") : match[0]);
  235 + });
  236 + }
  237 + return ((level === chain.length - 1) || !matches.length) ?
  238 + matches : recurseChain(matches, level + 1);
  239 + }([str], 0);
  240 + };
  241 +
  242 +
  243 + //---------------------------------
  244 + // New RegExp prototype methods
  245 + //---------------------------------
  246 +
  247 + // Accepts a context object and arguments array; returns the result of calling `exec` with the
  248 + // first value in the arguments array. the context is ignored but is accepted for congruity
  249 + // with `Function.prototype.apply`
  250 + RegExp.prototype.apply = function (context, args) {
  251 + return this.exec(args[0]);
  252 + };
  253 +
  254 + // Accepts a context object and string; returns the result of calling `exec` with the provided
  255 + // string. the context is ignored but is accepted for congruity with `Function.prototype.call`
  256 + RegExp.prototype.call = function (context, str) {
  257 + return this.exec(str);
  258 + };
  259 +
  260 +
  261 + //---------------------------------
  262 + // Overriden native methods
  263 + //---------------------------------
  264 +
  265 + // Adds named capture support (with backreferences returned as `result.name`), and fixes two
  266 + // cross-browser issues per ES3:
  267 + // - Captured values for nonparticipating capturing groups should be returned as `undefined`,
  268 + // rather than the empty string.
  269 + // - `lastIndex` should not be incremented after zero-length matches.
  270 + RegExp.prototype.exec = function (str) {
  271 + var match, name, r2, origLastIndex;
  272 + if (!this.global)
  273 + origLastIndex = this.lastIndex;
  274 + match = nativ.exec.apply(this, arguments);
  275 + if (match) {
  276 + // Fix browsers whose `exec` methods don't consistently return `undefined` for
  277 + // nonparticipating capturing groups
  278 + if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) {
  279 + r2 = RegExp(this.source, nativ.replace.call(getNativeFlags(this), "g", ""));
  280 + // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed
  281 + // matching due to characters outside the match
  282 + nativ.replace.call((str + "").slice(match.index), r2, function () {
  283 + for (var i = 1; i < arguments.length - 2; i++) {
  284 + if (arguments[i] === undefined)
  285 + match[i] = undefined;
  286 + }
  287 + });
  288 + }
  289 + // Attach named capture properties
  290 + if (this._xregexp && this._xregexp.captureNames) {
  291 + for (var i = 1; i < match.length; i++) {
  292 + name = this._xregexp.captureNames[i - 1];
  293 + if (name)
  294 + match[name] = match[i];
  295 + }
  296 + }
  297 + // Fix browsers that increment `lastIndex` after zero-length matches
  298 + if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index))
  299 + this.lastIndex--;
  300 + }
  301 + if (!this.global)
  302 + this.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows)
  303 + return match;
  304 + };
  305 +
  306 + // Fix browser bugs in native method
  307 + RegExp.prototype.test = function (str) {
  308 + // Use the native `exec` to skip some processing overhead, even though the altered
  309 + // `exec` would take care of the `lastIndex` fixes
  310 + var match, origLastIndex;
  311 + if (!this.global)
  312 + origLastIndex = this.lastIndex;
  313 + match = nativ.exec.call(this, str);
  314 + // Fix browsers that increment `lastIndex` after zero-length matches
  315 + if (match && !compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index))
  316 + this.lastIndex--;
  317 + if (!this.global)
  318 + this.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows)
  319 + return !!match;
  320 + };
  321 +
  322 + // Adds named capture support and fixes browser bugs in native method
  323 + String.prototype.match = function (regex) {
  324 + if (!XRegExp.isRegExp(regex))
  325 + regex = RegExp(regex); // Native `RegExp`
  326 + if (regex.global) {
  327 + var result = nativ.match.apply(this, arguments);
  328 + regex.lastIndex = 0; // Fix IE bug
  329 + return result;
  330 + }
  331 + return regex.exec(this); // Run the altered `exec`
  332 + };
  333 +
  334 + // Adds support for `${n}` tokens for named and numbered backreferences in replacement text,
  335 + // and provides named backreferences to replacement functions as `arguments[0].name`. Also
  336 + // fixes cross-browser differences in replacement text syntax when performing a replacement
  337 + // using a nonregex search value, and the value of replacement regexes' `lastIndex` property
  338 + // during replacement iterations. Note that this doesn't support SpiderMonkey's proprietary
  339 + // third (`flags`) parameter
  340 + String.prototype.replace = function (search, replacement) {
  341 + var isRegex = XRegExp.isRegExp(search),
  342 + captureNames, result, str, origLastIndex;
  343 +
  344 + // There are too many combinations of search/replacement types/values and browser bugs that
  345 + // preclude passing to native `replace`, so don't try
  346 + //if (...)
  347 + // return nativ.replace.apply(this, arguments);
  348 +
  349 + if (isRegex) {
  350 + if (search._xregexp)
  351 + captureNames = search._xregexp.captureNames; // Array or `null`
  352 + if (!search.global)
  353 + origLastIndex = search.lastIndex;
  354 + } else {
  355 + search = search + ""; // Type conversion
  356 + }
  357 +
  358 + if (Object.prototype.toString.call(replacement) === "[object Function]") {
  359 + result = nativ.replace.call(this + "", search, function () {
  360 + if (captureNames) {
  361 + // Change the `arguments[0]` string primitive to a String object which can store properties
  362 + arguments[0] = new String(arguments[0]);
  363 + // Store named backreferences on `arguments[0]`
  364 + for (var i = 0; i < captureNames.length; i++) {
  365 + if (captureNames[i])
  366 + arguments[0][captureNames[i]] = arguments[i + 1];
  367 + }
  368 + }
  369 + // Update `lastIndex` before calling `replacement` (fix browsers)
  370 + if (isRegex && search.global)
  371 + search.lastIndex = arguments[arguments.length - 2] + arguments[0].length;
  372 + return replacement.apply(null, arguments);
  373 + });
  374 + } else {
  375 + str = this + ""; // Type conversion, so `args[args.length - 1]` will be a string (given nonstring `this`)
  376 + result = nativ.replace.call(str, search, function () {
  377 + var args = arguments; // Keep this function's `arguments` available through closure
  378 + return nativ.replace.call(replacement + "", replacementToken, function ($0, $1, $2) {
  379 + // Numbered backreference (without delimiters) or special variable
  380 + if ($1) {
  381 + switch ($1) {
  382 + case "$": return "$";
  383 + case "&": return args[0];
  384 + case "`": return args[args.length - 1].slice(0, args[args.length - 2]);
  385 + case "'": return args[args.length - 1].slice(args[args.length - 2] + args[0].length);
  386 + // Numbered backreference
  387 + default:
  388 + // What does "$10" mean?
  389 + // - Backreference 10, if 10 or more capturing groups exist
  390 + // - Backreference 1 followed by "0", if 1-9 capturing groups exist
  391 + // - Otherwise, it's the string "$10"
  392 + // Also note:
  393 + // - Backreferences cannot be more than two digits (enforced by `replacementToken`)
  394 + // - "$01" is equivalent to "$1" if a capturing group exists, otherwise it's the string "$01"
  395 + // - There is no "$0" token ("$&" is the entire match)
  396 + var literalNumbers = "";
  397 + $1 = +$1; // Type conversion; drop leading zero
  398 + if (!$1) // `$1` was "0" or "00"
  399 + return $0;
  400 + while ($1 > args.length - 3) {
  401 + literalNumbers = String.prototype.slice.call($1, -1) + literalNumbers;
  402 + $1 = Math.floor($1 / 10); // Drop the last digit
  403 + }
  404 + return ($1 ? args[$1] || "" : "$") + literalNumbers;
  405 + }
  406 + // Named backreference or delimited numbered backreference
  407 + } else {
  408 + // What does "${n}" mean?
  409 + // - Backreference to numbered capture n. Two differences from "$n":
  410 + // - n can be more than two digits
  411 + // - Backreference 0 is allowed, and is the entire match
  412 + // - Backreference to named capture n, if it exists and is not a number overridden by numbered capture
  413 + // - Otherwise, it's the string "${n}"
  414 + var n = +$2; // Type conversion; drop leading zeros
  415 + if (n <= args.length - 3)
  416 + return args[n];
  417 + n = captureNames ? indexOf(captureNames, $2) : -1;
  418 + return n > -1 ? args[n + 1] : $0;
  419 + }
  420 + });
  421 + });
  422 + }
  423 +
  424 + if (isRegex) {
  425 + if (search.global)
  426 + search.lastIndex = 0; // Fix IE, Safari bug (last tested IE 9.0.5, Safari 5.1.2 on Windows)
  427 + else
  428 + search.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows)
  429 + }
  430 +
  431 + return result;
  432 + };
  433 +
  434 + // A consistent cross-browser, ES3 compliant `split`
  435 + String.prototype.split = function (s /* separator */, limit) {
  436 + // If separator `s` is not a regex, use the native `split`
  437 + if (!XRegExp.isRegExp(s))
  438 + return nativ.split.apply(this, arguments);
  439 +
  440 + var str = this + "", // Type conversion
  441 + output = [],
  442 + lastLastIndex = 0,
  443 + match, lastLength;
  444 +
  445 + // Behavior for `limit`: if it's...
  446 + // - `undefined`: No limit
  447 + // - `NaN` or zero: Return an empty array
  448 + // - A positive number: Use `Math.floor(limit)`
  449 + // - A negative number: No limit
  450 + // - Other: Type-convert, then use the above rules
  451 + if (limit === undefined || +limit < 0) {
  452 + limit = Infinity;
  453 + } else {
  454 + limit = Math.floor(+limit);
  455 + if (!limit)
  456 + return [];
  457 + }
  458 +
  459 + // This is required if not `s.global`, and it avoids needing to set `s.lastIndex` to zero
  460 + // and restore it to its original value when we're done using the regex
  461 + s = XRegExp.copyAsGlobal(s);
  462 +
  463 + while (match = s.exec(str)) { // Run the altered `exec` (required for `lastIndex` fix, etc.)
  464 + if (s.lastIndex > lastLastIndex) {
  465 + output.push(str.slice(lastLastIndex, match.index));
  466 +
  467 + if (match.length > 1 && match.index < str.length)
  468 + Array.prototype.push.apply(output, match.slice(1));
  469 +
  470 + lastLength = match[0].length;
  471 + lastLastIndex = s.lastIndex;
  472 +
  473 + if (output.length >= limit)
  474 + break;
  475 + }
  476 +
  477 + if (s.lastIndex === match.index)
  478 + s.lastIndex++;
  479 + }
  480 +
  481 + if (lastLastIndex === str.length) {
  482 + if (!nativ.test.call(s, "") || lastLength)
  483 + output.push("");
  484 + } else {
  485 + output.push(str.slice(lastLastIndex));
  486 + }
  487 +
  488 + return output.length > limit ? output.slice(0, limit) : output;
  489 + };
  490 +
  491 +
  492 + //---------------------------------
  493 + // Private helper functions
  494 + //---------------------------------
  495 +
  496 + // Supporting function for `XRegExp`, `XRegExp.copyAsGlobal`, etc. Returns a copy of a `RegExp`
  497 + // instance with a fresh `lastIndex` (set to zero), preserving properties required for named
  498 + // capture. Also allows adding new flags in the process of copying the regex
  499 + function clone (regex, additionalFlags) {
  500 + if (!XRegExp.isRegExp(regex))
  501 + throw TypeError("type RegExp expected");
  502 + var x = regex._xregexp;
  503 + regex = XRegExp(regex.source, getNativeFlags(regex) + (additionalFlags || ""));
  504 + if (x) {
  505 + regex._xregexp = {
  506 + source: x.source,
  507 + captureNames: x.captureNames ? x.captureNames.slice(0) : null
  508 + };
  509 + }
  510 + return regex;
  511 + }
  512 +
  513 + function getNativeFlags (regex) {
  514 + return (regex.global ? "g" : "") +
  515 + (regex.ignoreCase ? "i" : "") +
  516 + (regex.multiline ? "m" : "") +
  517 + (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3
  518 + (regex.sticky ? "y" : "");
  519 + }
  520 +
  521 + function runTokens (pattern, index, scope, context) {
  522 + var i = tokens.length,
  523 + result, match, t;
  524 + // Protect against constructing XRegExps within token handler and trigger functions
  525 + isInsideConstructor = true;
  526 + // Must reset `isInsideConstructor`, even if a `trigger` or `handler` throws
  527 + try {
  528 + while (i--) { // Run in reverse order
  529 + t = tokens[i];
  530 + if ((scope & t.scope) && (!t.trigger || t.trigger.call(context))) {
  531 + t.pattern.lastIndex = index;
  532 + match = t.pattern.exec(pattern); // Running the altered `exec` here allows use of named backreferences, etc.
  533 + if (match && match.index === index) {
  534 + result = {
  535 + output: t.handler.call(context, match, scope),
  536 + match: match
  537 + };
  538 + break;
  539 + }
  540 + }
  541 + }
  542 + } catch (err) {
  543 + throw err;
  544 + } finally {
  545 + isInsideConstructor = false;
  546 + }
  547 + return result;
  548 + }
  549 +
  550 + function indexOf (array, item, from) {
  551 + if (Array.prototype.indexOf) // Use the native array method if available
  552 + return array.indexOf(item, from);
  553 + for (var i = from || 0; i < array.length; i++) {
  554 + if (array[i] === item)
  555 + return i;
  556 + }
  557 + return -1;
  558 + }
  559 +
  560 +
  561 + //---------------------------------
  562 + // Built-in tokens
  563 + //---------------------------------
  564 +
  565 + // Augment XRegExp's regular expression syntax and flags. Note that when adding tokens, the
  566 + // third (`scope`) argument defaults to `XRegExp.OUTSIDE_CLASS`
  567 +
  568 + // Comment pattern: (?# )
  569 + XRegExp.addToken(
  570 + /\(\?#[^)]*\)/,
  571 + function (match) {
  572 + // Keep tokens separated unless the following token is a quantifier
  573 + return nativ.test.call(quantifier, match.input.slice(match.index + match[0].length)) ? "" : "(?:)";
  574 + }
  575 + );
  576 +
  577 + // Capturing group (match the opening parenthesis only).
  578 + // Required for support of named capturing groups
  579 + XRegExp.addToken(
  580 + /\((?!\?)/,
  581 + function () {
  582 + this.captureNames.push(null);
  583 + return "(";
  584 + }
  585 + );
  586 +
  587 + // Named capturing group (match the opening delimiter only): (?<name>
  588 + XRegExp.addToken(
  589 + /\(\?<([$\w]+)>/,
  590 + function (match) {
  591 + this.captureNames.push(match[1]);
  592 + this.hasNamedCapture = true;
  593 + return "(";
  594 + }
  595 + );
  596 +
  597 + // Named backreference: \k<name>
  598 + XRegExp.addToken(
  599 + /\\k<([\w$]+)>/,
  600 + function (match) {
  601 + var index = indexOf(this.captureNames, match[1]);
  602 + // Keep backreferences separate from subsequent literal numbers. Preserve back-
  603 + // references to named groups that are undefined at this point as literal strings
  604 + return index > -1 ?
  605 + "\\" + (index + 1) + (isNaN(match.input.charAt(match.index + match[0].length)) ? "" : "(?:)") :
  606 + match[0];
  607 + }
  608 + );
  609 +
  610 + // Empty character class: [] or [^]
  611 + XRegExp.addToken(
  612 + /\[\^?]/,
  613 + function (match) {
  614 + // For cross-browser compatibility with ES3, convert [] to \b\B and [^] to [\s\S].
  615 + // (?!) should work like \b\B, but is unreliable in Firefox
  616 + return match[0] === "[]" ? "\\b\\B" : "[\\s\\S]";
  617 + }
  618 + );
  619 +
  620 + // Mode modifier at the start of the pattern only, with any combination of flags imsx: (?imsx)
  621 + // Does not support x(?i), (?-i), (?i-m), (?i: ), (?i)(?m), etc.
  622 + XRegExp.addToken(
  623 + /^\(\?([imsx]+)\)/,
  624 + function (match) {
  625 + this.setFlag(match[1]);
  626 + return "";
  627 + }
  628 + );
  629 +
  630 + // Whitespace and comments, in free-spacing (aka extended) mode only
  631 + XRegExp.addToken(
  632 + /(?:\s+|#.*)+/,
  633 + function (match) {
  634 + // Keep tokens separated unless the following token is a quantifier
  635 + return nativ.test.call(quantifier, match.input.slice(match.index + match[0].length)) ? "" : "(?:)";
  636 + },
  637 + XRegExp.OUTSIDE_CLASS,
  638 + function () {return this.hasFlag("x");}
  639 + );
  640 +
  641 + // Dot, in dotall (aka singleline) mode only
  642 + XRegExp.addToken(
  643 + /\./,
  644 + function () {return "[\\s\\S]";},
  645 + XRegExp.OUTSIDE_CLASS,
  646 + function () {return this.hasFlag("s");}
  647 + );
  648 +
  649 +
  650 + //---------------------------------
  651 + // Backward compatibility
  652 + //---------------------------------
  653 +
  654 + // Uncomment the following block for compatibility with XRegExp 1.0-1.2:
  655 + /*
  656 + XRegExp.matchWithinChain = XRegExp.matchChain;
  657 + RegExp.prototype.addFlags = function (s) {return clone(this, s);};
  658 + RegExp.prototype.execAll = function (s) {var r = []; XRegExp.iterate(s, this, function (m) {r.push(m);}); return r;};
  659 + RegExp.prototype.forEachExec = function (s, f, c) {return XRegExp.iterate(s, this, f, c);};
  660 + RegExp.prototype.validate = function (s) {var r = RegExp("^(?:" + this.source + ")$(?!\\s)", getNativeFlags(this)); if (this.global) this.lastIndex = 0; return s.search(r) === 0;};
  661 + */
  662 +
  663 +})();
  664 +
... ...
Please register or login to post a comment