Home Backend Development PHP Tutorial Mail library in PHP8.0

Mail library in PHP8.0

May 14, 2023 am 08:49 AM
php programming Mail library

Recently, PHP8.0 released a new mail library, making it easier to send and receive emails in PHP. This library has powerful features including building emails, sending emails, parsing emails, getting attachments and solving email getting stuck issues.

In many projects, we need to use email for communication and some necessary business operations. The mail library in PHP8.0 allows us to achieve this easily. Next, we'll explore this new mail library and see how to use it in our application.

Install the mail library
First, we need to use Composer to install the PHP8.0 mail library. In our project directory, we can run the following command:

composer require phpmailer/phpmailer

This command will install the PHPMailer library, which is the standard mail library for PHP8.0.

Establishing a connection
Before we use the mail library, we need to establish a connection with the SMTP server. We can use SMTP protocol to send emails. The SMTP server requires an SMTP address and port. Using the mail library in PHP8.0, we can use the following code to establish a connection with the SMTP server:

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require 'vendor/autoload.php ';
$mail = new PHPMailer(true);

try {

//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
$mail->isSMTP();                                            //Send using SMTP
$mail->Host       = 'smtp.gmail.com';                       //Set the SMTP server to send through
$mail->SMTPAuth   = true;                                   //Enable SMTP authentication
$mail->Username   = 'yourname@gmail.com';                  //SMTP username
$mail->Password   = 'yourpassword';                         //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
$mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have no SSL/TLS support

//Recipients
$mail->setFrom('yourname@gmail.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');     //Add a recipient

//Content
$mail->isHTML(true);                                          //Set email format to HTML
$mail->Subject = 'Test Email';
$mail->Body    = 'This is a test email.';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();
echo 'Message has been sent';
Copy after login

} catch (Exception $e) {

echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
Copy after login

}

In the above code, we first introduced the PHPMailer library and created a PHPMailer instance. We then set up the SMTP server's address, port number and username, password, and enabled SMTP authentication. We also format and content the email and specify the sender and recipient addresses.

Using the mail library
After setting up the connection with the SMTP server, we can use the mail library of PHP8.0 to send emails. We can use the following code to send an email:

//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients' ;

$mail->send();

The isHTML() method in the above code is used to specify that the content of the email sent is in HTML format. The Subject attribute specifies the subject of the email, the Body attribute specifies the content of the email, and the AltBody attribute specifies the plain text content of the email so that it cannot be viewed using an HTML-formatted email client.

Parsing emails
The mail library of PHP8.0 also provides the function of parsing emails. We can use the following code to parse an email:

// Load the email message
$mail = new PHPMailer();
$mail->setServer('smtp.gmail. com', 'username', 'password');
$mail->setPort('587');
$mail->addAddress('recipient@example.com', 'John Doe') ;

// Retrieve the whole email content
$mail->retrieve();

// Convert the email body to a UTF-8 string
$emailBody = $mail->utf8ize($mail->Body);

// Parse the email using PHP's built-in imap functions
$imapStream = imap_open('{imap.gmail.com:993 /imap/ssl}INBOX', 'username', 'password');
$message = imap_fetchbody($imapStream, 1, "");

// Parse the email body using PHP's built- in DOM functions
$dom = new DOMDocument();
@$dom->loadHTML($emailBody);
$data = array();
$header = $dom-> getElementsByTagName('header')->item(0);
foreach($header->childNodes as $node) {

if ($node->nodeName == 'from') {
    list($name, $email) = explode(' <', $node->nodeValue);
    $data['from_name'] = $name;
    $data['from_email'] = str_replace('>', '', $email);
} elseif ($node->nodeName == 'date') {
    $data['date'] = date('Y-m-d H:i:s', strtotime($node->nodeValue));
} elseif ($node->nodeName == 'subject') {
    $data['subject'] = $node->nodeValue;
}
Copy after login

}

retrieve( in the above code ) method is used to retrieve the contents of the entire email. After converting the email content into UTF-8 format, we can use PHP's built-in imap function to parse the email. We can also use PHP's DOM functions to parse email header information.

Summary
PHP8.0’s mail library makes it easier to use email in PHP applications. The library provides powerful functionality including building emails, sending emails, parsing emails and getting attachments of emails. By using PHPMailer library we can easily implement mail functionality and use it in our application.

The above is the detailed content of Mail library in PHP8.0. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

See all articles