callback.phps 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * This example shows how to use a callback function from PHPMailer.
  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. /**
  10. * Example PHPMailer callback function.
  11. * This is a global function, but you can also pass a closure (or any other callable)
  12. * to the `action_function` property.
  13. * @param boolean $result result of the send action
  14. * @param array $to email address of the recipient
  15. * @param array $cc cc email addresses
  16. * @param array $bcc bcc email addresses
  17. * @param string $subject the subject
  18. * @param string $body the email body
  19. */
  20. function callbackAction($result, $to, $cc, $bcc, $subject, $body)
  21. {
  22. echo "Message subject: \"$subject\"\n";
  23. foreach ($to as $address) {
  24. echo "Message to {$address[1]} <{$address[0]}>\n";
  25. }
  26. foreach ($cc as $address) {
  27. echo "Message CC to {$address[1]} <{$address[0]}>\n";
  28. }
  29. foreach ($bcc as $toaddress) {
  30. echo "Message BCC to {$toaddress[1]} <{$toaddress[0]}>\n";
  31. }
  32. if ($result) {
  33. echo "Message sent successfully\n";
  34. } else {
  35. echo "Message send failed\n";
  36. }
  37. }
  38. require_once '../vendor/autoload.php';
  39. $mail = new PHPMailer;
  40. try {
  41. $mail->isMail();
  42. $mail->setFrom('you@example.com', 'Your Name');
  43. $mail->addAddress('jane@example.com', 'Jane Doe');
  44. $mail->addCC('john@example.com', 'John Doe');
  45. $mail->Subject = 'PHPMailer Test Subject';
  46. $mail->msgHTML(file_get_contents('../examples/contents.html'));
  47. // optional - msgHTML will create an alternate automatically
  48. $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
  49. $mail->addAttachment('images/phpmailer_mini.png'); // attachment
  50. $mail->action_function = 'callbackAction';
  51. $mail->send();
  52. } catch (Exception $e) {
  53. echo $e->errorMessage();
  54. }
  55. //Alternative approach using a closure
  56. try {
  57. $mail->action_function = function ($result, $to, $cc, $bcc, $subject, $body) {
  58. if ($result) {
  59. echo "Message sent successfully\n";
  60. } else {
  61. echo "Message send failed\n";
  62. }
  63. };
  64. $mail->send();
  65. } catch (Exception $e) {
  66. echo $e->errorMessage();
  67. }