exceptions.phps 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. /**
  3. * This example shows how to make use of PHPMailer's exceptions for error handling.
  4. */
  5. //Import PHPMailer classes into the global namespace
  6. use PHPMailer\PHPMailer\PHPMailer;
  7. use PHPMailer\PHPMailer\Exception;
  8. require '../vendor/autoload.php';
  9. //Create a new PHPMailer instance
  10. //Passing true to the constructor enables the use of exceptions for error handling
  11. $mail = new PHPMailer(true);
  12. try {
  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 Exceptions test';
  21. //Read an HTML message body from an external file, convert referenced images to embedded,
  22. //and convert the 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. //send the message
  29. //Note that we don't need check the response from this because it will throw an exception if it has trouble
  30. $mail->send();
  31. echo 'Message sent!';
  32. } catch (Exception $e) {
  33. echo $e->errorMessage(); //Pretty error messages from PHPMailer
  34. } catch (\Exception $e) { //The leading slash means the Global PHP Exception class will be caught
  35. echo $e->getMessage(); //Boring error messages from anything else!
  36. }