laravel PHPMailer code example
Example 1: phpmailer with laravel
composer require phpmailer/phpmailer
Example 2: phpmailer with laravel
<?php
namespace App\Http\Controllers;
use PHPMailer\PHPMailer;
class testPHPMailer extends Controller
{
public function index()
{
$text = 'Hello Mail';
$mail = new PHPMailer\PHPMailer();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "[email protected]";
$mail->Password = "testpass";
$mail->SetFrom("[email protected]", 'Sender Name');
$mail->Subject = "Test Subject";
$mail->Body = $text;
$mail->AddAddress("[email protected]", "Receiver Name");
if ($mail->Send()) {
return 'Email Sended Successfully';
} else {
return 'Failed to Send Email';
}
}
}
Example 3: phpmailer install composer
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp1.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'secret';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User');
$mail->addAddress('[email protected]');
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');
$mail->addAttachment('/var/tmp/file.tar.gz');
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');
$mail->isHTML(true);
$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';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}