简体   繁体   English

PHPmailer-在站点范围的文件中包含设置

[英]PHPmailer - include settings in site-wide file

I am setting up several scripts across a site with PHP mailer - all of which include common code to configure email settings, such as: 我正在使用PHP mailer在整个站点上设置多个脚本-所有这些脚本都包含用于配置电子邮件设置的通用代码,例如:

$mail = new PHPMailer;
$mail->isSMTP();                      // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';   // Specify main and backup server
$mail->Port = 587;                    // Set port
$mail->SMTPAuth = true;           // Enable SMTP authentication
$mail->Username = 'me@mail.com';
$mail->Password = 'PASSWORD'; 
$mail->Subject  = "My subject";
$mail->Body = 'Message here!!';

etc.. 等等..

I would like to set this information once in a site-wide 'settings.php' file? 我想一次在站点范围的“ settings.php”文件中设置此信息? Whilst I could do $mail->Port = $port; 虽然我可以做$mail->Port = $port; etc, I wondered if there is a better way to include all the code across the site, whilst still having the information in the settings file. 等等,我想知道是否有更好的方法可以将整个站点中的所有代码都包含在内,同时仍将信息保留在设置文件中。 The best way I can think of so far is three files: 到目前为止,我能想到的最好方法是三个文件:

File 1: settings.php 文件1:settings.php

$host = 'smtp.gmail.com';
$port = 587;
$SMTPAuth = true;
$Username = 'me@mail.com';
$Password = 'PASSWORD';

File 2: mailer_settings.php 文件2:mailer_settings.php

include('settings.php');

$mail->isSMTP();                      // Set mailer to use SMTP
$mail->Host = $host;      // Specify main and backup server
$mail->Port = $port;                      // Set port
$mail->SMTPAuth = $SMTPAuth;              // Enable SMTP authentication
$mail->Username = $Username;
$mail->Password = $Password; 

File 3: mailer_script.php 文件3:mailer_script.php

$mail = new PHPMailer;
include('mailer_settings.php');
$mail->Subject  = "My subject";
$mail->Body = 'Message here!!';

Is there an even more efficient way to do this? 有没有更有效的方法可以做到这一点?

You approach requires you to use the variable $mail every time you use PHPMailer. 您的方法要求您每次使用PHPMailer时都使用变量$mail

I'd rather suggest you writer a wrapper class, that takes config options as an array, and then creates a new PHPMailer instance, sets the options it was given, and returns the instance … 我宁愿建议您编写一个包装器类,该包装器类将config选项作为一个数组,然后创建一个新的PHPMailer实例,设置给定的选项,然后返回该实例……

Or instead of a wrapper class you could also extend the PHPMailer class, so that it calls its parent constructor and then sets the options. 或代替包装器类,您还可以扩展 PHPMailer类,以便它调用其父构造函数,然后设置选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM