亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Core Points
Comparison between PHPMailer and PHP mail() Functions
Installing PHPMailer
Send emails from local web server using PHPMailer
Send emails containing attachments
Troubleshooting
Show localization error message
Using SMTP
Retrieve emails using POP3
Conclusion
Frequently Asked Questions about PHPMailer
Home Backend Development PHP Tutorial Sending Emails in PHP with PHPMailer

Sending Emails in PHP with PHPMailer

Feb 08, 2025 am 10:37 AM

PHPMailer: a powerful tool for sending PHP mail

PHPMailer is a popular open source PHP mail delivery library. Since its release in 2001, it has been one of the preferred options for PHP developers to send programmatic emails, and is on par with other popular libraries such as Swiftmailer. This article will explain why PHPMailer is better than PHP's built-in mail() functions and provide code examples.

Sending Emails in PHP with PHPMailer

Core Points

  • PHPMailer is a popular open source PHP mail delivery library that provides more functionality and flexibility than PHP's built-in mail() functions, including object-oriented interfaces, easier HTML and attachment processing, and the use of non-local mail servers ability.
  • PHPMailer can be installed using Composer and is used by popular PHP content management systems such as WordPress, Drupal, and Joomla.
  • This library provides a powerful error handling mechanism, able to print error messages in more than 40 languages, and integrates SMTP protocol support as well as SSL and TLS authentication.
  • In addition to sending mail, PHPMailer also supports adding attachments, sending HTML or plain text versions of mail, and using SMTP to send mail from non-local servers, but it does not support retrieving mail from mail servers using POP3 protocol.

Comparison between PHPMailer and PHP mail() Functions

In most cases, PHPMailer is an alternative to PHP built-in mail() functions, but in many cases, the flexibility of the mail() functions is not enough to meet the needs.

First, PHPMailer provides an object-oriented interface, while the mail() function is not object-oriented. PHP developers generally don't like to create mail() strings when sending emails using $headers functions, because this requires a lot of escape operations. PHPMailer simplifies this process. When sending attachments and HTML-based mail using the mail() function, developers also need to write complex code (escaping characters, encoding and formatting), and PHPMailer makes this easy.

In addition, the mail() function requires a local mail server to send mail, which is not always easy to set. If authentication is available, PHPMailer can use a non-local mail server (SMTP).

Other advantages include:

  • When sending a message fails, it can print various error messages in more than 40 languages.
  • It integrates SMTP protocol support as well as SSL and TLS authentication.
  • It can send an alternative plain text version of messages to non-HTML mail clients.
  • It has a very active community of developers to keep it safe and up to date.

PHPMailer is also used by popular PHP content management systems such as WordPress, Drupal and Joomla.

Installing PHPMailer

PHPMailer can be installed using Composer:

composer require phpmailer/phpmailer

Send emails from local web server using PHPMailer

The following is the simplest example of sending mail from a local web server using PHPMailer:

composer require phpmailer/phpmailer

The code and comments in the PHP file should explain everything that is happening clearly enough; you can see where we set the email subject, sender email address, recipient email address, HTML email body, and Where to deal with errors.

Send emails containing attachments

The following is an example of how to use PHPMailer to send mail with attachments:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once "vendor/autoload.php";

// PHPMailer對(duì)象
$mail = new PHPMailer(true); // 構(gòu)造函數(shù)中的參數(shù)true啟用異常

// 發(fā)件人郵箱地址和名稱
$mail->From = "from@yourdomain.com";
$mail->FromName = "完整姓名";

// 收件人地址和名稱
$mail->addAddress("recepient1@example.com", "收件人姓名");
$mail->addAddress("recepient1@example.com"); // 收件人姓名是可選的

// 收件人回復(fù)地址
$mail->addReplyTo("reply@yourdomain.com", "回復(fù)");

// 抄送和密送
$mail->addCC("cc@example.com");
$mail->addBCC("bcc@example.com");

// 發(fā)送HTML或純文本郵件
$mail->isHTML(true);

$mail->Subject = "主題文本";
$mail->Body = "<i>HTML格式郵件正文</i>";
$mail->AltBody = "這是郵件內(nèi)容的純文本版本";

try {
    $mail->send();
    echo "郵件已成功發(fā)送";
} catch (Exception $e) {
    echo "郵件錯(cuò)誤:" . $mail->ErrorInfo;
}
?>

Here, we attach two files - file.txt (located in the same directory as the script) and images/profile.png (located in the images directory of the script directory).

To add attachments to a mail, we simply call the addAttachment function of the PHPMailer object by passing the file path as a parameter. To attach multiple files, we need to call it multiple times.

Troubleshooting

In our two examples, we used the Exception class of PHPMailer for debugging, so any errors thrown will help us debug any issues that may occur. We also added the parameter true to the PHPMailer constructor to output higher-level, more descriptive exceptions.

Depending on the system we are using, the biggest error we may see will be related to running the mail() function in the background:

Mail Error: The mail function cannot be instantiated.

If we need more detailed error information, we can also add the following to the catch clause:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once "vendor/autoload.php";

$mail = new PHPMailer;

$mail->From = "from@yourdomain.com";
$mail->FromName = "完整姓名";

$mail->addAddress("recipient1@example.com", "收件人姓名");

// 提供附件的文件路徑和名稱
$mail->addAttachment("file.txt", "File.txt");
$mail->addAttachment("images/profile.png"); // 文件名是可選的

$mail->isHTML(true);

$mail->Subject = "主題文本";
$mail->Body = "<i>HTML格式郵件正文</i>";
$mail->AltBody = "這是郵件內(nèi)容的純文本版本";

try {
    $mail->send();
    echo "郵件已成功發(fā)送";
} catch (Exception $e) {
    echo "郵件錯(cuò)誤:" . $mail->ErrorInfo;
}
?>

Usually, the problem with the mail function will be related to the missing mail server settings, in which case the error_get_last function will return something like the following:

print_r(error_get_last());

This is probably the most common problem we have, and we can easily solve it by using SMTP.

Show localization error message

$mail->ErrorInfo can return error messages in 43 different languages.

To display error messages in different languages, copy the language directory from the source code of PHPMailer to the project directory.

For example, to return an error message in Russian, set the PHPMailer object to Russian using the following method call:

<code>Array (
    [type] => 2
    [message] => mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
    [file] => OUR_PATH \vendor\phpmailer\phpmailer\src\PHPMailer.php
    [line] => 863
)</code>

You can also add your own language files to the language directory.

Using SMTP

You can send mail using another host's mail server, but this requires authentication first. For example, to send mail from Gmail's mail server, you need to have a Gmail account.

SMTP is a protocol used by the mail client to send mail requests to the mail server. After the mail server verifies the mail, it is sent to the target mail server.

The following is an example of sending mail from your domain from your Gmail mail server. You don't need a local server to run the code. We will use the SMTP protocol:

composer require phpmailer/phpmailer

Gmail requires TLS encryption via SMTP, so we set it accordingly. Before sending over SMTP, you need to find out the host name, port number, whether the encryption type is required and if authentication is required, the username and password are also required. Note that enabling two-factor authentication on Gmail will not allow you to use its SMTP with your username/password. Instead, additional configuration is required.

One of the big advantages of using remote SMTP instead of local mail is that if you use PHP's mail() function to send mail and set the sender address domain to anything different from the local domain name (server name), The recipient's email server's attack filter marks it as spam. For example, if you send an email to name@yahoo.com from a server with hostname example.com using the sender address name@gmail.com, Yahoo's server will mark it as spam, or display a message to the user , instructing not to trust the message, because the source of the message is example.com, but it appears from gmail.com. Even though you have name@gmail.com, Yahoo has no way of knowing this.

Retrieve emails using POP3

PHPMailer also allows POP-before-SMTP verification to send mail. In other words, you can authenticate using POP and send mail using SMTP. Unfortunately, PHPMailer does not support retrieving mail from a mail server using the POP3 protocol. It is limited to sending mail only.

Conclusion

If you are a PHP developer, it is almost impossible to avoid sending emails programmatically. While you can choose third-party services like Mandrill or SendGrid, sometimes this is simply not feasible, and even more so when writing your own email sending library. This is where PHPMailer and its alternatives (Zend Mail, Swift Mailer, etc.) come into play.

You can learn about the API about this library in the repository wiki or in the official documentation.

Are you troubled by PHP library dependencies? Watch our screen recording to see how Composer can help you manage it.

Frequently Asked Questions about PHPMailer

What is PHPMailer? PHPMailer is a popular open source PHP library for sending emails from PHP applications. It provides a simple and flexible way to send emails via SMTP, mail() or other email sending methods.

How to install PHPMailer? You can use Composer to install PHPMailer, or you can download the library directly from GitHub. Detailed installation instructions can be found in the PHPMailer documentation.

Is PHPMailer free to use? Yes, PHPMailer is open source and released under the LGPL license, which means it is available for free in open source and commercial projects.

What are the system requirements for PHPMailer? PHPMailer is compatible with PHP 5.5 and later. Make sure your web hosting environment supports these PHP versions.

How to send emails using PHPMailer? You can use PHPMailer to send emails by creating an instance of the PHPMailer class, setting necessary properties such as SMTP server details and email content, and then calling the send() method.

Can PHPMailer handle attachments in emails? Yes, PHPMailer provides methods to add attachments to your emails. You can attach files from a server or remote location.

What is SMTP and why should I use it with PHPMailer? SMTP (Simple Mail Transfer Protocol) is a common method for sending emails. Using SMTP with PHPMailer allows you to send emails through a remote email server, providing better control and reliability for email delivery.

Can I send HTML emails with PHPMailer?

Yes, PHPMailer allows you to send emails in plain text and HTML formats. You can set the message type and format accordingly. Plain text email is suitable for non-HTML mail clients.

Can I use PHPmailer to send plain text emails to non-HTML mail clients?

Yes, PHPMailer allows you to send plain text emails as an alternative to HTML emails. You can set the message type and format accordingly. Plain text email is suitable for non-HTML mail clients.

Can I use PHPMailer with a non-SMTP mail server such as Sendmail? Yes, PHPMailer supports a variety of email transfer methods, including SMTP, mail(), and other custom methods, allowing you to use it with different types of mail servers.

Sending Emails in PHP with PHPMailer

The above is the detailed content of Sending Emails in PHP with PHPMailer. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

php regex for password strength php regex for password strength Jul 03, 2025 am 10:33 AM

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

See all articles