PHPMailer is perhaps the most popular open-source PHP library to send emails with.
first Download PhpMailer from https://github.com/PHPMailer/PHPMailer
1)
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;
}
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
No comments:
Post a Comment