phpmailer example smtp

Example 1: php mailer

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$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 TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->setFrom('[email protected]', '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->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';
}

Example 2: core php mail function without phpmailer

<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

session_start();

$to = '[email protected]';
$subject = 'Subject xxxxx xxxxxx';

$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=charset=utf-8\r\n";
$headers .= "From: " . $_POST['email'] . "\r\n";
//$headers .= "Reply-To: ". $_POST['email'] . "\r\n";
$headers .= "CC: [email protected]\r\n";



$message = "<html><body>";

$message .= '<table style="border-color: #666; background: #eee; cellpadding="10">';
$message .= "<tr><td><strong>Name:</strong> </td><td>" . $_POST['username'] . "</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>" . $_POST['email'] . "</td></tr>"; 


$message .= "</table>";
$message .= "</body></html>";


echo $message;
//echo $headers;



$response=mail($to, $subject, $message, $headers);

if($response==1)
{
echo "<script language='javascript' type='text/javascript'>
        
       window.location = 'index.html';
    </script>";

}
else{
echo 
"<script language='javascript' type='text/javascript'>
        alert('mail send failed');
    </script>";
}



?>

Example 3: require php mailer

composer require phpmailer/phpmailer