Sending emails is a common requirement for many web applications, and PHP provides several ways to achieve this. In this tutorial, we will explore the different methods of sending emails using PHP, including the built-in mail()
function, PHPMailer, and other libraries.
Introduction to Email Sending in PHP
Before we dive into the details, it’s essential to understand the basics of email sending in PHP. When you send an email using PHP, you need to specify the recipient’s email address, the subject of the email, and the message body. You can also add additional headers, such as the sender’s email address and name.
Using the Built-in mail()
Function
The mail()
function is a built-in PHP function that allows you to send emails. It takes four arguments: the recipient’s email address, the subject of the email, the message body, and additional headers.
Here is an example of how to use the mail()
function:
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Note that the mail()
function will not work on a local server, and you need to have a mail server configured to use it.
Using PHPMailer
PHPMailer is a popular library for sending emails in PHP. It provides a more robust and flexible way of sending emails compared to the built-in mail()
function. You can download PHPMailer from its GitHub repository and include it in your PHP script.
Here is an example of how to use PHPMailer:
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = '[email protected]';
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]', 'Joe User'); // Add a recipient
$mail->addAddress('[email protected]'); // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Sending HTML Emails
To send HTML emails, you need to specify the Content-type
header as text/html
. You can do this using the mail()
function or PHPMailer.
Here is an example of how to send an HTML email using the mail()
function:
$to = '[email protected]';
$subject = 'Birthday Reminders for August';
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
Using Other Libraries
There are several other libraries available for sending emails in PHP, including Swift Mailer and PEAR Mail. These libraries provide a more robust and flexible way of sending emails compared to the built-in mail()
function.
Here is an example of how to use Swift Mailer:
require 'mail/swift_required.php';
$message = Swift_Message::newInstance()
->setSubject('Jane Doe sends you a message')
->setFrom(array('[email protected]' => 'Jane Doe'))
->setTo(array('[email protected]' => 'Frank Stevens'))
->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
echo json_encode([
"status" => "OK",
"message" => 'Your message has been sent!'
], JSON_PRETTY_PRINT);
} else {
echo json_encode([
"status" => "error",
"message" => 'Oops! Something went wrong!'
], JSON_PRETTY_PRINT);
}
Conclusion
In this tutorial, we have explored the different methods of sending emails using PHP, including the built-in mail()
function, PHPMailer, and other libraries. We have also covered how to send HTML emails and use additional headers. By following this tutorial, you should be able to send emails using PHP with ease.