For a new project, install PHPMailer with Composer and load it through vendor/autoload.php. This avoids the old manual class.phpmailer.php include pattern shown later on this page.
<?php
require __DIR__ . '/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
$mail->setFrom('no-reply@example.com', 'Example Site');
$mail->addAddress('recipient@example.com');
$mail->Subject = 'Test message';
$mail->Body = 'This message was sent with PHPMailer.';
$mail->send();
?>
The older class-file installation examples below are preserved as legacy reference. Use the Composer/autoload approach for current projects.
To post mails from website phpmailer is much better and easy to use than using PHP mail() function. require_once('my_phpmailer/class.phpmailer.php');
We kept this file inside my_phpmailer folder, you can change the path as per your site condition. $email = new PHPMailer();
Most of our job is over now. Here is the full code to send your first mail using phpmailer.
<?php
$bodytext=' This is the body of the test mail ';
$subject= 'plus2 Message Subject'.date(" H:i:s", time());
require_once('my_phpmailer/class.phpmailer.php');
$email = new PHPMailer();
$email->From = 'userid@example.com';
$email->AddReplyTo('userid@example.com', 'Contact Admin');
$email->FromName = 'Your Name';
$email->Subject = $subject;
$email->Body = $bodytext;
$email->AddAddress('userid1@example.com');
$email->AddAddress('userid2@example.com');
if(!$email->send())
{
echo "Mailer Error: " . $email->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
?>
$email->Body = $bodytext;
$email->IsHTML(true);// HTML email
$email->AddCC('userid3@example.com');
$email->AddBCC('userid4@example.com');
$file_to_attach = 'your_dir/top.pdf'; // Path with file name
$email->AddAttachment( $file_to_attach);// File attached
The full code with file attachement is here.
<?php
$bodytext=' This is the body of the test mail ';
$subject= 'plus2 Message Subject'.date(" H:i:s", time());
require_once('my_phpmailer/class.phpmailer.php');
$email = new PHPMailer();
$email->From = 'userid@example.com';
$email->AddReplyTo('userid@example.com', 'Contact Admin');
$email->FromName = 'Your Name';
$email->Subject = $subject;
$email->Body = $bodytext;
$email->AddAddress('userid1@example.com');
$email->AddAddress('userid2@example.com');
$file_to_attach = 'your_dir/top.pdf'; // Path with file name
$email->AddAttachment( $file_to_attach);// File attached
if(!$email->send())
{
echo "Mailer Error: " . $email->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
06-04-2021 | |
| Just downloaded PHPMailer 6.4.0 but it does not contain the class.phpmailer.php file? | |