PHP Email Sending and Receiving: Text, HTML, and Attachment Handling
This article explains how to use PHP functions and PHPMailer to send and receive emails in plain text, HTML, and with attachments, covering proper encoding, header configuration, IMAP retrieval, and code examples for each scenario.
In modern society, email is a crucial communication tool, and when using PHP for sending and receiving emails, proper content formatting ensures readability and correct display. This guide covers handling of plain text, HTML, and attachments.
1. Text Format Email Sending and Receiving
For simple text emails, the PHP mail() function can be used. Proper encoding and headers are required to display the content correctly.
$to = "[email protected]";
$subject = "Testing email";
$message = "This is a test email.";
$headers = "From: [email protected]
";
$headers .= "MIME-Version: 1.0
";
$headers .= "Content-Type: text/plain; charset=UTF-8
";
mail($to, $subject, $message, $headers);To receive text emails, PHP's IMAP functions can be used to connect to the mail server and fetch the body.
$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 Format Email Sending and Receiving
For emails containing HTML, PHPMailer or similar libraries are recommended. The Content-Type header must be set to text/html .
require 'vendor/autoload.php';
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'username';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Recipients
$mail->setFrom('[email protected]', 'Sender Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Testing email';
$mail->isHTML(true);
$mail->Body = '
This is a test email.
';
$mail->send();
echo 'Email has been sent.';
} catch (Exception $e) {
echo 'Email could not be sent. Error: ', $mail->ErrorInfo;
}Receiving HTML emails can be done with imap_fetchbody() specifying the part that contains HTML.
$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); // part 2 usually holds HTML
// Process email content
// ...
}
imap_close($mailbox);3. Attachment Handling
PHPMailer simplifies adding attachments when sending emails.
require 'vendor/autoload.php';
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
$mail = new PHPMailer(true);
try {
// Server settings (same as above)
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'username';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Recipients and content
$mail->setFrom('[email protected]', 'Sender Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Testing email';
$mail->isHTML(true);
$mail->Body = '
This is a test email.
';
$mail->addAttachment('/path/to/file.pdf');
$mail->send();
echo 'Email has been sent.';
} catch (Exception $e) {
echo 'Email could not be sent. Error: ', $mail->ErrorInfo;
}Receiving attachments involves parsing the email structure and saving each part marked as a filename.
$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;
$structure = imap_fetchstructure($mailbox, $i);
// Iterate over parts to find attachments
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);
// Further processing of the attachment
// ...
}
}
}
}
// Process email content
// ...
}
imap_close($mailbox);Conclusion
By using PHP functions and libraries such as PHPMailer, developers can reliably send and receive emails in text, HTML, and with attachments, ensuring proper formatting and readability.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.