Home > Backend Development > PHP Tutorial > How can I send HTML emails reliably using PHP and PHPMailer?

How can I send HTML emails reliably using PHP and PHPMailer?

Mary-Kate Olsen
Release: 2024-11-09 13:36:02
Original
372 people have browsed it

How can I send HTML emails reliably using PHP and PHPMailer?

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
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template