为了账号安全,请及时绑定邮箱和手机立即绑定

PHPMAILER 将电子邮件配置分离到不同的功能中

PHPMAILER 将电子邮件配置分离到不同的功能中

PHP
弑天下 2022-08-19 16:43:48
PHPMAILER在我的网站上工作正常。我想做的是将配置部分分成一个单独的函数,这样当我创建不同的响应电子邮件时,我需要做的就是在不同的响应函数中调用该函数。emailConfig()function continuedInquiry() {    //config portion I want to separate    $mail = new PHPMailer;    $mail->isSMTP();    $mail->SMTPDebug = SMTP::DEBUG_OFF;    $mail->Host = 'smtp.gmail.com';    $mail->Port = 587;    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;    $mail->SMTPAuth = true;    $mail->Username = 'example@gmail.com';    $mail->Password = 'password';    /**      *rest of the phpmailer code    */    $mail->send();    notify();}function notify() {    //notification email    $mail = new PHPMailer;    $mail->isSMTP();    $mail->SMTPDebug = SMTP::DEBUG_OFF;    $mail->Host = 'smtp.gmail.com';    $mail->Port = 587;    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;    $mail->SMTPAuth = true;    $mail->Username = 'example@gmail.com';    $mail->Password = 'password';    /**      *rest of the phpmailer code     */}这按预期工作,但是因为我使用的是多个邮件程序,因此我想将配置部分分成一个单独的函数,如下所示:emailConfig()function emailConfig() {    $mail = new PHPMailer;    $mail->isSMTP();    $mail->SMTPDebug = SMTP::DEBUG_OFF;    $mail->Host = 'smtp.gmail.com';    $mail->Port = 587;    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;    $mail->SMTPAuth = true;    $mail->Username = 'example@gmail.com';    $mail->Password = 'password';}并在其他邮件程序函数中调用它:function continuedInquiry() {    emailConfig();    /**      *rest of the phpmailer code    */    $mail->send();    notify();}//and so on但是我不断收到一个错误,说$mail没有定义:我尝试过返回,我尝试过争论。这将简化事情,但我无法让它工作。
查看完整描述

1 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

您可能会发现使用子类来配置它更容易,如下所示:


<?php


use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\SMTP;


class myMailer extends PHPMailer

{

    public function __construct($exceptions = null)

    {

        $this->isSMTP();

        $this->SMTPDebug = SMTP::DEBUG_OFF;

        $this->Host = 'smtp.gmail.com';

        $this->Port = 587;

        $this->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

        $this->SMTPAuth = true;

        $this->Username = 'example@gmail.com';

        $this->Password = 'password';

        parent::__construct($exceptions);

    }

}

然后在脚本中,您可以执行以下操作:


$mail = new myMailer(true);

它将完成所有配置,随时可以使用。


也就是说,最好将“机密”(如密码)从代码中移出到外部环境变量或配置文件中,这样您就不会最终将密码推送到 git 存储库中。


查看完整回答
反对 回复 2022-08-19
  • 1 回答
  • 0 关注
  • 99 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号