自定义php函数中的PHPMailer [英] PHPMailer in a custom php function

查看:81
本文介绍了自定义php函数中的PHPMailer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个定制类函数,用于设置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非常陌生,任何小的答案都可能对我有所帮助,谢谢。

推荐答案

您的代码似乎没有问题,但更好的方法可能是调用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);

这篇关于自定义php函数中的PHPMailer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆