【问题标题】:PHPMailer in a custom php function自定义php函数中的PHPMailer
【发布时间】:2016-12-13 06:23:41
【问题描述】:

我做了一个自定义类函数来设置PHPMailer所需的基本信息(所以我不需要每次都输入)。这是函数的确切代码。

<?php

class PHPMailer {

    public static function send() {// I will just add here the addAddress
        require_once 'mail/PHPMailerAutoload.php';

        $mail = new PHPMailer;

        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'html';
        $mail->Host = "smtp.gmail.com";
        $mail->Port = 587;
        $mail->SMTPSecure = 'tls';
        $mail->SMTPAuth = true;
        $mail->Username = "validusername";
        $mail->Password = "validpassword";
        $mail->setFrom('validusername', 'Valid Username');
        $mail->addAddress('googol8080@gmail.com', 'Googol');

        $mail->Subject = "Subject";
        $mail->Body    = "<a href=\"www.google.com\">www.google.com</a>";
        $mail->IsHTML(true);

        if (!$mail->send()) {
            return "Error sending message" . $mail->ErrorInfo;
        } else {
            return "Message sent!";
        }
    }
}

到目前为止,它正在我的本地主机上运行,​​但我有问题:

  • 这是一个好的做法吗?
  • 代码正常吗?
  • 这有什么缺点吗?
  • 如果需要在此处优化性能,我需要做些什么来实现它?

我是 PHP 和 PHPMailer 的新手,任何小的答案都可能对我有帮助,谢谢。

【问题讨论】:

    标签: php phpmailer


    【解决方案1】:

    你的代码看起来不错,但更好的方法是调用variables,这样你就不必每次调用类时都配置它。

    class phpmailer {
        public function sendMail($email, $message, $subject)
        {
            require_once('../phpmailer/class.phpmailer.php');
            require_once('../phpmailer/class.smtp.php');
            require_once('../phpmailer/class.pop3.php');
            $mail = new PHPMailer();
            $mail->isSMTP();
            $mail->SMTPDebug = 0;
            $mail->SMTPAuth = true;
            $mail->SMTPSecure = "ssl";
            $mail->Host = "smtp.gmail.com";
            $mail->Port = 465;
            $mail->addAddress($email);
            $mail->Username = "email@gmail.com";
            $mail->Password = "email_password";
            $mail->setFrom('email_Sent_from@gmail.com', 'Alias');
            $mail->addReplyTo("email_to@gmail.com", "Alias");
            $mail->Subject = $subject;
            $mail->msgHTML($message);
            $mail->send();
        }
    }
    

    那么你可以这样称呼它:

    $email_send = new phpmailer();
    $email_send->sendMail($user_email,$message,$subject);
    

    【讨论】:

    • 请问这3个require_once的目的是什么?谢谢。
    • 第一个用于php mailer类,第二个和第三个用于smtp和pop3,如果你想使用它们
    • 啊,好的,谢谢,顺便说一句,当我尝试发送一封简单的电子邮件(本地主机)时,发送最多需要 2 秒。可以吗?我的意思是我使用的是本地主机,它最多需要 2 秒,如果我在生产中使用它(共享主机)会发生什么?最多可能需要 2 到 5 秒?
    • 那是正常的老兄:)
    • 我知道这已经很老了,但我只是尝试了上面的方法,得到了这个错误:Fatal error: Uncaught Error: Call to undefined method phpmailer::isSMTP()有什么想法吗?
    猜你喜欢
    • 2016-08-03
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2016-07-08
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    相关资源
    最近更新 更多