ارسال ایمیل در PHP با PHPMailer
https://www.sitepoint.com/sending-emails-php-phpmailer/?utm_source=rss
PHPMailer is perhaps the most popular open-source PHP library 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.
Is It an Alternative to PHP’s mail() Function?
In most cases, it’s an alternative to PHP’s mail() function, but there are many other cases where the mail() function is simply not flexible enough to achieve what you need.
First of all, PHPMailer provides an object-oriented interface, whereas mail() is not object oriented. PHP developers generally hate to create $headers strings while sending emails using the mail() function because they require a lot of escaping. PHPMailer makes this a breeze. Developers also need to write dirty code (escaping characters, encoding and formatting) to send attachments and HTML based emails when using the mail() function, whereas PHPMailer makes this painless.
Also, the mail() function requires a local mail server to send out emails, which is not always trivial to set up. PHPMailer can use a non-local mail server (SMTP) if you have authentication.
Further advantages include:
- It can print various kinds of error messages in more than 40 languages when it fails to send an email.
- It has integrated SMTP protocol support and authentication over SSL and TLS.
- It can send an alternative plain-text version of email for non-HTML email clients.
- It has a very active developer community that keeps it secure and up to date.
PHPMailer is also used by popular PHP content management systems like WordPress, Drupal, and Joomla.
Installing PHPMailer
You can install PHPMailer using Composer:
composer require phpmailer/phpmailer
Sending Email from a Local Web Server Using PHPMailer
Here’s the simplest example of sending an email from a local web server using PHPMailer:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once "vendor/autoload.php";
//PHPMailer Object
$mail = new PHPMailer(true); //Argument true in constructor enables exceptions
//From email address and name
$mail->From = "from@yourdomain.com";
$mail->FromName = "Full Name";
//To address and name
$mail->addAddress("recepient1@example.com", "Recepient Name");
$mail->addAddress("recepient1@example.com"); //Recipient name is optional
//Address to which recipient will reply
$mail->addReplyTo("reply@yourdomain.com", "Reply");
//CC and BCC
$mail->addCC("cc@example.com");
$mail->addBCC("bcc@example.com");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
The code and comments should be sufficiently clear to explain everything that’s going on.
Sending an Email with Attachments
Here’s an example of how to send an email with attachments using PHPMailer:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once "vendor/autoload.php";
$mail = new PHPMailer;
$mail->From = "from@yourdomain.com";
$mail->FromName = "Full Name";
$mail->addAddress("recipient1@example.com", "Recipient Name");
//Provide file path and name of the attachments
$mail->addAttachment("file.txt", "File.txt");
$mail->addAttachment("images/profile.png"); //Filename is optional
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
Here, we’re attaching two files — file.txt , which resides in the same directory as the script, and images/profile.png , which 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.
Troubleshooting
In our two examples, we used PHPMailer’s Exception class for debugging, so any errors thrown will help us debug any issues that may occur. We also added the argument true to PHPMailer constructor, to output higher-level, more descriptive exceptions.
Depending on the system we use, probably the most frequent error we’ll see will be related to running the mail() function in the background:
Mailer Error: Could not instantiate mail function.
If we need more details on the error, we can also add something like this to the catch clause:
print_r(error_get_last());
Usually, the problem with the mail function will be related to the missing mail server setup, in which case the error_get_last function will return something like this:
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
)
This is the issue we’ll probably encounter most frequently, and we can solve it easily by using SMTP.
Continue reading
Sending Emails in PHP with PHPMailer
on SitePoint.
|