extending.phps 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * This example shows how to extend PHPMailer to simplify your coding.
  4. * If PHPMailer doesn't do something the way you want it to, or your code
  5. * contains too much boilerplate, don't edit the library files,
  6. * create a subclass instead and customise that.
  7. * That way all your changes will be retained when PHPMailer is updated.
  8. */
  9. //Import PHPMailer classes into the global namespace
  10. use PHPMailer\PHPMailer\PHPMailer;
  11. use PHPMailer\PHPMailer\Exception;
  12. require '../vendor/autoload.php';
  13. /**
  14. * Use PHPMailer as a base class and extend it
  15. */
  16. class myPHPMailer extends PHPMailer
  17. {
  18. /**
  19. * myPHPMailer constructor.
  20. * @param bool|null $exceptions
  21. * @param string $body A default HTML message body
  22. */
  23. public function __construct($exceptions, $body = '')
  24. {
  25. //Don't forget to do this or other things may not be set correctly!
  26. parent::__construct($exceptions);
  27. //Set a default 'From' address
  28. $this->setFrom('joe@example.com', 'Joe User');
  29. //Send via SMTP
  30. $this->isSMTP();
  31. //Equivalent to setting `Host`, `Port` and `SMTPSecure` all at once
  32. $this->Host = 'tls://smtp.example.com:587';
  33. //Set an HTML and plain-text body, import relative image references
  34. $this->msgHTML($body, './images/');
  35. //Show debug output
  36. $this->SMTPDebug = 2;
  37. //Inject a new debug output handler
  38. $this->Debugoutput = function ($str, $level) {
  39. echo "Debug level $level; message: $str\n";
  40. };
  41. }
  42. //Extend the send function
  43. public function send()
  44. {
  45. $this->Subject = '[Yay for me!] ' . $this->Subject;
  46. $r = parent::send();
  47. echo "I sent a message with subject ". $this->Subject;
  48. return $r;
  49. }
  50. }
  51. //Now creating and sending a message becomes simpler when you use this class in your app code
  52. try {
  53. //Instantiate your new class, making use of the new `$body` parameter
  54. $mail = new myPHPMailer(true, '<strong>This is the message body</strong>');
  55. // Now you only need to set things that are different from the defaults you defined
  56. $mail->addAddress('jane@example.com', 'Jane User');
  57. $mail->Subject = 'Here is the subject';
  58. $mail->addAttachment(__FILE__, 'myPHPMailer.php');
  59. $mail->send(); //no need to check for errors - the exception handler will do it
  60. } catch (Exception $e) {
  61. //Note that this is catching the PHPMailer Exception class, not the global \Exception type!
  62. echo "Caught a ".get_class($e).": " . $e->getMessage();
  63. }