Send Emails in PHP using PHPMailer

0 104

PHPMailer is one of the most popular open source PHP libraries to send emails with. It was first released way back in 2001 and since then it has become a PHP developer’s favorite way of sending emails programmatically, aside from a few other fan favorites like Swiftmailer.

In this article we’ll talk about why you should use PHPMailer instead of PHP’s mail() function and we’ll show some code samples on how to use this library.

Further advantages include:

  • It can print various kinds of errors messages in more than 40 languages when it fails to send an email
  • Integrated SMTP protocol support and authentication over SSL and TLS
  • Can send alternative plaintext version of email for non-HTML email clients
  • Very active developer community which keeps it secure and up to date

PHPMailer is also used by popular PHP content management systems like WordPress, Drupal, Joomla etc.

Installing PHPMailer

You can install PHPMailer using Composer:

Sending Email from Local Web Server using PHPMailer

Here is the simplest example of sending an email from a local web server using PHPMailer

The code and comments should be sufficiently clear to explain everything that’s going on.

Sending an E-Mail with Attachments

Let’s see an example on how to send an email with attachments using PHPMailer.

Here we are attaching two files i.e., file.txt which resides in the same directory as the script and images/profile.pngwhich resides in images directory of the script directory.

To add attachments to the email we just need to call the function addAttachment of the PHPMailer object by passing the file path as argument. For attaching multiple files we need to call it multiple times.

Using SMTP

You can use the mail server of an another host to send email, but for this you first need to have authentication. For example: to send an email from Gmail’s mail server you need to have a Gmail account.

SMTP is a protocol used by mail clients to send an email send request to a mail server. Once the mail server verifies the email it sends it to the destination mail server.

Here is an example of sending an email from Gmail’s mail server from your domain. You don’t need a local mail server to run the code. We will be using the SMTP protocol:


Displaying Localized Error Messages

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

To display error messages in a different language, copy the language directory from PHPMailer’s source code to the project directory.

To return error messages in, for example, Russian, set the PHPMailer object to the Russian language using the below method call:

You might also like More from author

Leave A Reply

Your email address will not be published.