Sending HTML Email: SMTP Configuration for PHP
Although the email sending example shows using PHP to send HTML email, frustratingly, It doesn't work correctly. Specifically, it produces a blank email in Gmail with an empty file named "noname" attached.
To solve this problem, consider using the PHPMailer class. This is a popular and well-maintained PHP library designed to simplify the email sending process. With PHPMailer, you can easily create and send HTML emails, attach files, set priorities, and process attachments.
To get started, install PHPMailer through Composer:
composer require phpmailer/phpmailer
Once installed, you can write the following code to send HTML emails using PHPMailer:
use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(true); try { // 设置服务器的信息 $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'username@example.com'; $mail->Password = 'password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; // 设置发件人 $mail->setFrom('from@example.com', 'From Name'); // 添加收件人 $mail->addAddress('to@example.com', 'To Name'); // 设置主题和内容 $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Test HTML email'; $mail->Body = '<h1>Hello World!</h1><p>This is an <b>HTML</b> email.</p>'; // 发送邮件 $mail->send(); echo 'Message has been sent using PHPMailer'; } catch (Exception $e) { echo 'Message could not be sent. Error: ', $mail->ErrorInfo; }
By using PHPMailer, you can reliably send HTML mail without having to manually deal with the complexities of SMTP configuration.
The above is the detailed content of How can I send HTML emails reliably using PHP and PHPMailer?. For more information, please follow other related articles on the PHP Chinese website!