How to send email using phpmailer

How to send email using phpmailer?

  • Using phpmailer, send an email : code is given bellow –
<?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();                                            //Send using SMTP
    $mail->Host       = 'smtp.codeloveguru.com'; 				        // Host name                    
    $mail->SMTPAuth   = true;                                   
    $mail->Username   = 'smtp_user_name@codeloveguru.com';      //SMTP username
    $mail->Password   = 'smtp_user_password';                   //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;           
    $mail->Port       = 465;                                    //TCP port


    $mail->setFrom('from_mail_id@codeloveguru.com', 'Mailer');
    $mail->addAddress('ashok@codeloveguru.net', 'Ashok User');     
    $mail->addAddress('ramesh@codeloveguru.com');               
    $mail->addReplyTo('info123@codeloveguru.com', 'Information');
    $mail->addCC('cc_mail_id@codeloveguru.com');
    $mail->addBCC('bcc_email_id@codeloveguru.com');

    $mail->addAttachment('/var/tmp/attachfile.pdf');            //adding attachments
    $mail->addAttachment('/tmp/newimage.jpg', 'abc.jpg');       //Optional 

    $mail->isHTML(true);                                       //send email HTML format
    $mail->Subject = 'The mail subject here';
    $mail->Body    = 'HTML message body here';
    $mail->AltBody = 'plain text for non-HTML mail users';

    $mail->send();
    echo 'The email has been sent successfully';
} catch (Exception $e) {
    echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>
  • The bellow code defines the library of PHP mail.
  • This code must be added at top of your script, not inside a function.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
  • The bellow code defines the HTML format message/ body of email –
$mail->isHTML(true);                                  //send email HTML format
$mail->Subject = 'The mail subject here';
$mail->Body    = 'HTML message body here';
$mail->AltBody = 'plain text for non-HTML mail users';
  • The given code defines the attachment files with the email.
 $mail->addAttachment('/var/tmp/attachfile.pdf');            //adding attachments
 $mail->addAttachment('/tmp/newimage.jpg', 'abc.jpg');       //Optional
  • The bellow code defines CC mail ID and BCC Email ID –
  $mail->addCC('cc_mail_id@codeloveguru.com');
  $mail->addBCC('bcc_email_id@codeloveguru.com');

How to send email using phpmailer

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *