如何使 "PHPmailer "在一个函数中工作?

问题描述 投票:0回答:1

我不知道如何在函数中使用PHPmailer发送邮件。

我想做一些类似于这样的事情--当我想发送邮件时,我只需要调用一个函数(比如send::mail())。

<?php
require '.\vendor\autoload.php';

//PHPMailer Object
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->IsSendmail();
//From email address and name
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->setFrom('[email protected]', 'Bot name');
$mail->Password = "########";                       // SMTP password
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;         
//To address and name
$mail->addAddress("[email protected]"); //Recipient name is optional

//Address to which recipient will reply

//Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
$mail->Mailer = "sendmail";
if(!$mail->send()) 
{
    echo "Mailer Error: " . $mail->ErrorInfo;
}
?>

谁能帮我把它写成一个函数? 当我试过的时候, "使用 "命令不起作用.

php function class email phpmailer
1个回答
0
投票

首先,你必须确定数据。

    $mailHost = '';
    $mailSMTPAuth = '';
    $mailUsername = '';
    $mailPassword = '';
    $mailSMTPSecure = '';
    $mailPort = '';
    $mailSenderAddress = '';
    $mailSenderName = '';

然后,你可以生成一个只包含收件人、主题和消息的函数,你可以通过将设置拉到这个函数中来轻松发送邮件。

function sendMail($sendMailAdress, $sendMailName, $sendMailSubject, $sendMailMessage) {
    global $mailHost;
    global $mailSMTPAuth;
    global $mailUsername;
    global $mailPassword;
    global $mailSMTPSecure;
    global $mailPort;
    global $mailSenderAddress;
    global $mailSenderName;

    require_once('class/phpmailer/PHPMailerAutoload.php');
    $mail = new PHPMailer;
    $mail->isSMTP(); // Set mailer to use SMTP
    $mail->Host = $mailHost; // Specify main and backup SMTP servers
    $mail->SMTPAuth = $mailSMTPAuth; // Enable SMTP authentication
    $mail->Username = $mailUsername; // SMTP username or mail
    $mail->Password = $mailPassword; // SMTP password
    $mail->SMTPSecure = $mailSMTPSecure; // Enable TLS encryption, `ssl` also accepted
    $mail->Port = $mailPort; // TCP port to connect to
    $mail->CharSet = 'utf-8';
    $mail->setFrom($mailSenderAddress, $mailSenderName);
    $mail->addAddress($sendMailAdress, $sendMailName); // Add a recipient
    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = $sendMailSubject;
    $mail->Body = $sendMailMessage;
    if(!$mail->send()) {
        return false;
    } else {
        return true;
    }
}

这个函数的工作原理是这样的:

sendMail('[email protected]', 'Test User', 'Subject of test mail', 'And your mail message);
© www.soinside.com 2019 - 2024. All rights reserved.