WordPress phpmailer 自定义插件

发布于 2025-01-13 16:47:03 字数 10586 浏览 0 评论 0原文

我已经从 html/php 网站更改为当地居民协会的 wordpress cms 网站,除了电子邮件位之外,一切都很好。 我对 WordPress 的唯一体验是过去几个月我玩得很开心的自定义构建,我没有真正理解 WordPress 与 phpmailer 的反应,除了一个版本被包装在 wp_mail 中,这是我试图避免的,希望能够去直接到我的服务器。 我有一个现有的 phpmailer smtp 脚本,在旧站点上运行得很好,我尝试了各种方法在 WordPress 上实现此功能,但没有成功,我发现如果我将其设为插件,那么很多问题就会消失,例如格式化页面等,在我看来这很重要。 有人可以帮助我或向我解释为什么这不起作用以及我必须做什么才能让这个脚本工作。

  /**
   * Author: <a href="[email protected]">tony</a>
   * Version: 1.0.0
   * Plugin Name: Email Form Plugin
   * Description: This is a Contact Us Page Email Form Plugin
   **/
  
   function email_form_plugin()
   {
     $content = '';
     $content .= '<h3>Contact Us</h3>';
     $content .= '<form method="post" action="">';
     $content .= '<select class="select" name="recipients" id="recipients">
     <option value="choose_recipient" selected>Choose Recipient</option>
     <option value="chair">Chair :&emsp; John Smith</option>
     <option value="vice_chair">Vice Chair :&emsp; Linda Smith</option>
     <option value="secretary">Secretary :&emsp; Terry Smith</option>
     <option value="treasurer">Treasurer :&emsp; Colin Smith</option>
     <option value="membership_secretary">Membership Secretary :&emsp; Victor Smith</option>
     <option value="highways_officer">Highways Officer :&emsp; Richard Smith</option>
     <option value="environmental_officer">Environmental Officer :&emsp; Martin Smith</option>
     <option value="schools_liaison_officer">Schools Liaison Officer :&emsp; Julie Smith</option>
     <option value="events_co-ordinator">Events Co-ordinator :&emsp; Susan Smith</option>
     <option value="webmaster">Webmaster :&emsp; David Smith</option>
     <option value="suggestion">Suggestion :&emsp; RA Committee</option>
   </select>';
  
     $content .= '<select class="select" name="title">                        
     <option value="" selected>Choose Your Title</option>
     <option value="Mr">Mr</option>
     <option value="Mrs">Mrs</option>
     <option value="Miss">Miss</option>
     <option value="Ms">Ms</option>
   </select>';
  
     $content .= '<input type="text" name="firstname" class="select" id="firstname" maxlength="20" placeholder="Enter First Name" pattern="[A-Za-z]+" title="Please use letters only, no other characters" autocomplete="off" required>';
  
     $content .= '<input type="text" name="lastname" class="select" id="lastname" maxlength="30" placeholder="Enter Last Name" pattern="[A-Za-z\s]+" title="Please use letters and spaces only, no other characters" autocomplete="off" required>';
  
     $content .= '<input type="email" name="email" class="select" id="email" maxlength="55" placeholder="Enter Email Address" pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" title="Please make sure your email address is correct" autocomplete="off" required>';
  
     $content .= '<input type="tel" name="mobile" class="select" placeholder="Enter Mobile/Phone Number" pattern="^[0-9\s]*$" title="Please use numbers and spaces only" autocomplete="off">';
  
     $content .= '<input type="text" name="topic" class="select" id="topic" maxlength="60" placeholder="Enter Your Topic" pattern="[a-zA-Z0-9\s]+" title="Please use letters, numbers and spaces only, no other characters" autocomplete="off" required>';
  
     $content .= '<textarea cols="60" rows="8" name="info" class="select" id="info" placeholder="Write Your Question or Suggestion Here!" title="Please write your question or suggestion here!" autocomplete="off" required></textarea>';
      
     $content .= '<div id="entry1" class="attachment-row"> 
     <input name="attachment[]" class="select" type="file" id="attachment" multiple="multiple"> 
   </div>';
  
     $content .= '<div onClick="addMoreAttachment();" id="btnAdd" name="btnAdd" class="icon-add-more-attachemnt" title="Add More Attachments">
     <p>Add More Attachments &ensp;
     <img width="16" height="16" src="https://test.uk/wp-content/uploads/2022/01/icon-add-more-attachment.png" alt="Add More Attachments"></p>        
   </div>';
  
     $content .= '<div><br> <button type="submit" class="btn btn--dark-purple" name="email_form_submit">Send Email</button> </div>';
  
     $content .='</form>';
  
     return $content;
  
   }
   add_shortcode('email_form', 'email_form_plugin');
   
  // all above works fine and renders well on the contact page.
  //-----------------------------------------------------------
  //session_start();
  
  use PHPMailer\PHPMailer\PHPMailer;
  use PHPMailer\PHPMailer\Exception;
  use PHPMailer\PHPMailer\SMTP;
  
  require_once(\ABSPATH . \WPINC . "/PHPMailer/PHPMailer.php");
  require_once(\ABSPATH . \WPINC . "/PHPMailer/Exception.php");       
  require_once(\ABSPATH . \WPINC . "/PHPMailer/SMTP.php");
  
  $results = '';
  
  if (array_key_exists('attachment', $_FILES)) {
  
    $mail = new PHPMailer();
  
    $title = $_POST['title'];
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];
    $topic = $_POST['topic'];    
    $info = $_POST['info'];   
  
      $addresses = [
          'choose_recipient' =>         '[email protected]',  // used as a default recipient if no recipient chosen.
          'chair' =>                    '[email protected]',
          'vice_chair' =>               '[email protected]',
          'secretary' =>                '[email protected]',
          'treasurer' =>                '[email protected]',
          'membership_secretary' =>     '[email protected]',
          'highways_officer' =>         '[email protected]',
          'environmental_officer' =>    '[email protected]',
          'schools_liaison_officer' =>  '[email protected]',
          'events_co-ordinator' =>      '[email protected]',
          'webmaster' =>                '[email protected]',
          'suggestion' =>               '[email protected]',
      ];
          
      if (array_key_exists('recipients', $_POST) && array_key_exists($_POST['recipients'], $addresses)) {
    $mail->addAddress($addresses[$_POST['recipients']]);
      } else {
    //Fall back to fixed address if selection invalid
    $mail->addAddress('[email protected]');
      }       
  
      
      $mail->isSMTP();
      $mail->HOST        = 'mail.test.uk';
      $mail->SMTPAuth    = true;
      $mail->Port        = 465;
      $mail->Username    = '[email protected]';
      $mail->Password    = '************';
      $mail->SMTPSecure  = 'ssl';
      $mail->From        = '[email protected]';
      $mail->FromName    = 'RA';
      $mail->SMTPDebug   = 2; 
      
      $mail->setFrom($email, $firstname, $lastname);
      $mail->isHTML(true);                                  
      $mail->Subject = $topic;
  
          $body = 
              "<h2> Residents' Association </h2>
              <h3>You have received a message from our contact form:</h3>
              From: $title $firstname $lastname <br><br>      
              Email Contact: $email <br><br>
              Phone Contact: $mobile <br><br>
              Regarding: $topic <br><br>
              Message: $info <br><br>";  
      $mail->Body    = $body;
      $mail->AltBody = strip_tags($body);
  
      for ($ct = 0, $ctMax = count($_FILES['attachment']['tmp_name']); $ct < $ctMax; $ct++) {
          $ext = PHPMailer::mb_pathinfo($_FILES['attachment']['name'][$ct], PATHINFO_EXTENSION);              
          $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name'][$ct])) . '.' . $ext;
          $filename = $_FILES['attachment']['name'][$ct];
          if (move_uploaded_file($_FILES['attachment']['tmp_name'][$ct], $uploadfile)) {
              if (!$mail->addAttachment($uploadfile, $filename)) {
                  $results = "Failed to attach file " . $filename;
              }
          } else {
             // $results = "Failed to move file to " . $uploadfile;  //  if I send email without attachment - I get error message
          }
      }
  
  
      if (!$mail->send()) {
          $results = "Something went wrong......";
      } else {
        $result="Your inquiry has been submitted, a member of our team will get in touch with you within 24 hours.";
  }
  }  
  
  ?> ```


I have change over from a html/php website to a wordpress cms website for our local residents association, all is fine except for the email bit.
My only experience of wordpress is the custom build I have had fun with over the past few months, I have no real understanding how wordpress reacts with phpmailer, except that a version is wrapped in wp_mail, which I was trying to avoid, hoping to go direct to my server.
I have an existing phpmailer smtp script that works great on the old site, I have tried various methods to implement this on wordpress, with no success, I figured out that if I make it a plugin then a lot of problems disappear, like formatting on the page etc, in my mind this is important.
Can someone please help me or explain to me why this is not working and what I must do to get this script to work.

  /**
   * Author: <a href="[email protected]">tony</a>
   * Version: 1.0.0
   * Plugin Name: Email Form Plugin
   * Description: This is a Contact Us Page Email Form Plugin
   **/
  
   function email_form_plugin()
   {
     $content = '';
     $content .= '<h3>Contact Us</h3>';
     $content .= '<form method="post" action="">';
     $content .= '<select class="select" name="recipients" id="recipients">
     <option value="choose_recipient" selected>Choose Recipient</option>
     <option value="chair">Chair :  John Smith</option>
     <option value="vice_chair">Vice Chair :  Linda Smith</option>
     <option value="secretary">Secretary :  Terry Smith</option>
     <option value="treasurer">Treasurer :  Colin Smith</option>
     <option value="membership_secretary">Membership Secretary :  Victor Smith</option>
     <option value="highways_officer">Highways Officer :  Richard Smith</option>
     <option value="environmental_officer">Environmental Officer :  Martin Smith</option>
     <option value="schools_liaison_officer">Schools Liaison Officer :  Julie Smith</option>
     <option value="events_co-ordinator">Events Co-ordinator :  Susan Smith</option>
     <option value="webmaster">Webmaster :  David Smith</option>
     <option value="suggestion">Suggestion :  RA Committee</option>
   </select>';
  
     $content .= '<select class="select" name="title">                        
     <option value="" selected>Choose Your Title</option>
     <option value="Mr">Mr</option>
     <option value="Mrs">Mrs</option>
     <option value="Miss">Miss</option>
     <option value="Ms">Ms</option>
   </select>';
  
     $content .= '<input type="text" name="firstname" class="select" id="firstname" maxlength="20" placeholder="Enter First Name" pattern="[A-Za-z]+" title="Please use letters only, no other characters" autocomplete="off" required>';
  
     $content .= '<input type="text" name="lastname" class="select" id="lastname" maxlength="30" placeholder="Enter Last Name" pattern="[A-Za-z\s]+" title="Please use letters and spaces only, no other characters" autocomplete="off" required>';
  
     $content .= '<input type="email" name="email" class="select" id="email" maxlength="55" placeholder="Enter Email Address" pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}
quot; title="Please make sure your email address is correct" autocomplete="off" required>';
  
     $content .= '<input type="tel" name="mobile" class="select" placeholder="Enter Mobile/Phone Number" pattern="^[0-9\s]*
quot; title="Please use numbers and spaces only" autocomplete="off">';
  
     $content .= '<input type="text" name="topic" class="select" id="topic" maxlength="60" placeholder="Enter Your Topic" pattern="[a-zA-Z0-9\s]+" title="Please use letters, numbers and spaces only, no other characters" autocomplete="off" required>';
  
     $content .= '<textarea cols="60" rows="8" name="info" class="select" id="info" placeholder="Write Your Question or Suggestion Here!" title="Please write your question or suggestion here!" autocomplete="off" required></textarea>';
      
     $content .= '<div id="entry1" class="attachment-row"> 
     <input name="attachment[]" class="select" type="file" id="attachment" multiple="multiple"> 
   </div>';
  
     $content .= '<div onClick="addMoreAttachment();" id="btnAdd" name="btnAdd" class="icon-add-more-attachemnt" title="Add More Attachments">
     <p>Add More Attachments  
     <img width="16" height="16" src="https://test.uk/wp-content/uploads/2022/01/icon-add-more-attachment.png" alt="Add More Attachments"></p>        
   </div>';
  
     $content .= '<div><br> <button type="submit" class="btn btn--dark-purple" name="email_form_submit">Send Email</button> </div>';
  
     $content .='</form>';
  
     return $content;
  
   }
   add_shortcode('email_form', 'email_form_plugin');
   
  // all above works fine and renders well on the contact page.
  //-----------------------------------------------------------
  //session_start();
  
  use PHPMailer\PHPMailer\PHPMailer;
  use PHPMailer\PHPMailer\Exception;
  use PHPMailer\PHPMailer\SMTP;
  
  require_once(\ABSPATH . \WPINC . "/PHPMailer/PHPMailer.php");
  require_once(\ABSPATH . \WPINC . "/PHPMailer/Exception.php");       
  require_once(\ABSPATH . \WPINC . "/PHPMailer/SMTP.php");
  
  $results = '';
  
  if (array_key_exists('attachment', $_FILES)) {
  
    $mail = new PHPMailer();
  
    $title = $_POST['title'];
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];
    $topic = $_POST['topic'];    
    $info = $_POST['info'];   
  
      $addresses = [
          'choose_recipient' =>         '[email protected]',  // used as a default recipient if no recipient chosen.
          'chair' =>                    '[email protected]',
          'vice_chair' =>               '[email protected]',
          'secretary' =>                '[email protected]',
          'treasurer' =>                '[email protected]',
          'membership_secretary' =>     '[email protected]',
          'highways_officer' =>         '[email protected]',
          'environmental_officer' =>    '[email protected]',
          'schools_liaison_officer' =>  '[email protected]',
          'events_co-ordinator' =>      '[email protected]',
          'webmaster' =>                '[email protected]',
          'suggestion' =>               '[email protected]',
      ];
          
      if (array_key_exists('recipients', $_POST) && array_key_exists($_POST['recipients'], $addresses)) {
    $mail->addAddress($addresses[$_POST['recipients']]);
      } else {
    //Fall back to fixed address if selection invalid
    $mail->addAddress('[email protected]');
      }       
  
      
      $mail->isSMTP();
      $mail->HOST        = 'mail.test.uk';
      $mail->SMTPAuth    = true;
      $mail->Port        = 465;
      $mail->Username    = '[email protected]';
      $mail->Password    = '************';
      $mail->SMTPSecure  = 'ssl';
      $mail->From        = '[email protected]';
      $mail->FromName    = 'RA';
      $mail->SMTPDebug   = 2; 
      
      $mail->setFrom($email, $firstname, $lastname);
      $mail->isHTML(true);                                  
      $mail->Subject = $topic;
  
          $body = 
              "<h2> Residents' Association </h2>
              <h3>You have received a message from our contact form:</h3>
              From: $title $firstname $lastname <br><br>      
              Email Contact: $email <br><br>
              Phone Contact: $mobile <br><br>
              Regarding: $topic <br><br>
              Message: $info <br><br>";  
      $mail->Body    = $body;
      $mail->AltBody = strip_tags($body);
  
      for ($ct = 0, $ctMax = count($_FILES['attachment']['tmp_name']); $ct < $ctMax; $ct++) {
          $ext = PHPMailer::mb_pathinfo($_FILES['attachment']['name'][$ct], PATHINFO_EXTENSION);              
          $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name'][$ct])) . '.' . $ext;
          $filename = $_FILES['attachment']['name'][$ct];
          if (move_uploaded_file($_FILES['attachment']['tmp_name'][$ct], $uploadfile)) {
              if (!$mail->addAttachment($uploadfile, $filename)) {
                  $results = "Failed to attach file " . $filename;
              }
          } else {
             // $results = "Failed to move file to " . $uploadfile;  //  if I send email without attachment - I get error message
          }
      }
  
  
      if (!$mail->send()) {
          $results = "Something went wrong......";
      } else {
        $result="Your inquiry has been submitted, a member of our team will get in touch with you within 24 hours.";
  }
  }  
  
  ?> ```


如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑寡妇 2025-01-20 16:47:03

我建议不要包含您自己的 PHPMailer 副本,因为当 WordPress 中的内容更新时,它不太可能被更新。

您可以通过编写一个函数来获取 WordPress 的 PHPMailer 实例,然后将该函数链接到 WordPress 的 phpmailer_init 挂钩:

add_action('phpmailer_init', 'mailer_config');
function mailer_config(PHPMailer $mailer){
  $mailer->isSMTP();
  $mailer->Host = "mail.example.com"; // your SMTP server
  $mailer->Port = 25;
  $mailer->SMTPDebug = 2;
  $mailer->CharSet  = "utf-8";
  //etc
}

设置完毕后,当您调用 wp_mail( )

另外,要创建模板,您会发现使用 PHP 的 heredoc 语法 比所有这些连接操作。

I recommend not including your own copy of PHPMailer as it's less likely to be updated when things are updated in WordPress.

You can get hold of WordPress' PHPMailer instance by writing a function that you can then link to WordPress' phpmailer_init hook:

add_action('phpmailer_init', 'mailer_config');
function mailer_config(PHPMailer $mailer){
  $mailer->isSMTP();
  $mailer->Host = "mail.example.com"; // your SMTP server
  $mailer->Port = 25;
  $mailer->SMTPDebug = 2;
  $mailer->CharSet  = "utf-8";
  //etc
}

Having set that up, this config will then be used when you call wp_mail().

Separately, to create your template, you'll find it much easier to work with PHP's heredoc syntax than all those concat operations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文