Handling Email Sending and Receiving with PHP: Text, HTML, and Attachments

This article explains how to use PHP functions and libraries to send and receive plain‑text, HTML, and attachment‑rich emails, covering proper encoding, MIME headers, IMAP retrieval, and PHPMailer configuration for reliable email communication.

php Courses
php Courses
php Courses
Handling Email Sending and Receiving with PHP: Text, HTML, and Attachments

In modern society, email is a key communication tool, and PHP provides functions to format and handle email content for readability and proper display.

1. Text Email Sending and Receiving

For simple plain‑text emails, the built‑in mail() function can be used; proper charset and MIME headers must be set. Example code shows setting $to, $subject, $message and $headers before calling mail().

$to = "[email protected]";
$subject = "Testing email";
$message = "This is a test email.";
$headers = "From: [email protected]<br/>";
$headers .= "MIME-Version: 1.0<br/>";
$headers .= "Content-Type: text/plain; charset=UTF-8<br/>";
mail($to, $subject, $message, $headers);

Receiving plain‑text emails can be done with the IMAP extension: imap_open() connects to the mailbox, imap_num_msg() gets the message count, and a loop with imap_header() and imap_fetchbody() retrieves each message.

$mailbox = imap_open("{mail.example.com:993/imap/ssl}INBOX", "username", "password");
$messageCount = imap_num_msg($mailbox);
for ($i = 1; $i <= $messageCount; $i++) {
    $header = imap_header($mailbox, $i);
    $subject = $header->subject;
    $fromAddress = $header->fromaddress;
    $message = imap_fetchbody($mailbox, $i, 1);
    // process email content
}
imap_close($mailbox);

2. HTML Email Sending and Receiving

When sending HTML content, libraries such as PHPMailer are recommended. The example configures SMTP, sets From/To, enables HTML, assigns an HTML body, and sends the message, handling errors via exceptions.

require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'username';
    $mail->Password = 'password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;
    $mail->setFrom('[email protected]', 'Sender Name');
    $mail->addAddress('[email protected]', 'Recipient Name');
    $mail->Subject = 'Testing email';
    $mail->isHTML(true);
    $mail->Body = '<h1>This is a test email.</h1>';
    $mail->send();
    echo 'Email has been sent.';
} catch (Exception $e) {
    echo 'Email could not be sent. Error: ', $mail->ErrorInfo;
}

Receiving HTML mail also uses imap_fetchbody() with the part index for the HTML part.

$mailbox = imap_open("{mail.example.com:993/imap/ssl}INBOX", "username", "password");
$messageCount = imap_num_msg($mailbox);
for ($i = 1; $i <= $messageCount; $i++) {
    $header = imap_header($mailbox, $i);
    $subject = $header->subject;
    $fromAddress = $header->fromaddress;
    $message = imap_fetchbody($mailbox, $i, 2); // HTML part
    // process email content
}
imap_close($mailbox);

3. Attachment Handling

PHPMailer can add attachments with addAttachment(). Receiving attachments involves parsing the message structure with imap_fetchstructure(), iterating parts, detecting the filename parameter, fetching the body part, and saving it to a local file.

$mailbox = imap_open("{mail.example.com:993/imap/ssl}INBOX", "username", "password");
$messageCount = imap_num_msg($mailbox);
for ($i = 1; $i <= $messageCount; $i++) {
    $header = imap_header($mailbox, $i);
    $structure = imap_fetchstructure($mailbox, $i);
    foreach ($structure->parts as $partNum => $part) {
        if ($part->ifdparameters) {
            foreach ($part->dparameters as $param) {
                if (strtolower($param->attribute) == 'filename') {
                    $attachmentName = $param->value;
                    $attachmentData = imap_fetchbody($mailbox, $i, $partNum+1);
                    file_put_contents($attachmentName, $attachmentData);
                }
            }
        }
    }
    // process email content
}
imap_close($mailbox);

Conclusion: By using PHP’s mail, IMAP functions and libraries like PHPMailer, developers can reliably send and receive plain‑text, HTML, and attachment‑rich emails while ensuring proper encoding and display.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendHTML emailEmailattachmentSMTPIMAPPHPMailer
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.