In web applications, it is often necessary to send emails to multiple recipients at one time. PHP is a very popular web development language, and PHPMailer is a common PHP class library for sending emails. PHPMailer provides a rich interface, making sending emails in PHP applications more convenient and easy to use. In this article, we will introduce the methods and steps on how to use PHPMailer to send emails to multiple recipients.
First you need to download the PHPMailer class library on the official website (https://github.com/PHPMailer/PHPMailer). After the download is complete, unzip the compressed package and copy its folder to the location of the project.
In the PHP file, you need to introduce the PHPMailer class library. Class libraries can be introduced using require or include statements, as shown below:
require 'path/to/PHPMailer/src/Exception.php'; require 'path/to/PHPMailer/src/PHPMailer.php'; require 'path/to/PHPMailer/src/SMTP.php';
In the PHP file, you need to create a PHPMailer instance. The method of creating an instance is as follows:
$mail = new PHPMailerPHPMailerPHPMailer();
To send mail to multiple recipients, you must configure SMTP information. In the PHP code, you need to set the address, username and password of the SMTP server. PHPMailer provides SMTP options, which can easily enable SMTP to send emails. In the PHP code, you can use the following statements to configure SMTP information:
$mail->isSMTP(); // 设置使用SMTP发送邮件 $mail->Host = 'smtp.gmail.com'; // 设置SMTP服务器地址 $mail->SMTPAuth = true; // 启用SMTP身份验证 $mail->Username = 'username@gmail.com'; // SMTP用户名 $mail->Password = 'password'; // SMTP密码 $mail->SMTPSecure = 'tls'; // 启用TLS加密,也可以设置为ssl $mail->Port = 587; // SMTP端口号
In the PHP code, you need to set the sender information ( Including name and email address):
$mail->setFrom('from@example.com', 'From Name');
In the PHP code, you need to set the recipient information (multiple recipients can be set ):
$mail->addAddress('example1@example.com', 'Example 1'); $mail->addAddress('example2@example.com', 'Example 2');
In the PHP code, you need to set the email subject and content:
$mail->Subject = 'Subject'; $mail->Body = 'This is the body text'; $mail->AltBody = 'This is the plain text';
In PHP code, you can choose to add attachments:
$mail->addAttachment('/path/to/file.pdf'); // 添加附件
In PHP code, you can Send emails by calling the send() method of the PHPMailer instance:
if($mail->send()) { echo 'Message sent successfully'; } else { echo 'Message could not be sent'; }
After completing the above steps, you can successfully send emails to multiple recipients. I hope this article can be helpful to PHP developers.
The above is the detailed content of PHP methods and steps for sending emails to multiple people using PHPMailer. For more information, please follow other related articles on the PHP Chinese website!