Home >Backend Development >PHP Tutorial >Sending Emails in PHP with PHPMailer
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.
mail()
functions, including object-oriented interfaces, easier HTML and attachment processing, and the use of non-local mail servers ability. 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:
PHPMailer is also used by popular PHP content management systems such as WordPress, Drupal and Joomla.
PHPMailer can be installed using Composer:
<code class="language-bash">composer require phpmailer/phpmailer</code>
The following is the simplest example of sending mail from a local web server using PHPMailer:
<code class="language-bash">composer require phpmailer/phpmailer</code>
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.
The following is an example of how to use PHPMailer to send mail with attachments:
<code class="language-php"><?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require_once "vendor/autoload.php"; // PHPMailer对象 $mail = new PHPMailer(true); // 构造函数中的参数true启用异常 // 发件人邮箱地址和名称 $mail->From = "from@yourdomain.com"; $mail->FromName = "完整姓名"; // 收件人地址和名称 $mail->addAddress("recepient1@example.com", "收件人姓名"); $mail->addAddress("recepient1@example.com"); // 收件人姓名是可选的 // 收件人回复地址 $mail->addReplyTo("reply@yourdomain.com", "回复"); // 抄送和密送 $mail->addCC("cc@example.com"); $mail->addBCC("bcc@example.com"); // 发送HTML或纯文本邮件 $mail->isHTML(true); $mail->Subject = "主题文本"; $mail->Body = "<i>HTML格式邮件正文</i>"; $mail->AltBody = "这是邮件内容的纯文本版本"; try { $mail->send(); echo "邮件已成功发送"; } catch (Exception $e) { echo "邮件错误:" . $mail->ErrorInfo; } ?></code>
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.
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:
<code class="language-php"><?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 = "这是邮件内容的纯文本版本"; try { $mail->send(); echo "邮件已成功发送"; } catch (Exception $e) { echo "邮件错误:" . $mail->ErrorInfo; } ?></code>
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:
<code class="language-php">print_r(error_get_last());</code>
This is probably the most common problem we have, and we can easily solve it by using SMTP.
$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.
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:
<code class="language-bash">composer require phpmailer/phpmailer</code>
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.
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.
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.
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.
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!