Send Email via SMTP Server in PHP using PHPMailer

PHPMailer Library:

// Include PHPMailer library files
require 'PHPMailer-master/PHPMailerAutoload.php';
// Create an instance of PHPMailer class
$mail = new PHPMailer;

Note that: You don’t need to download PHPMailer library separately. All the required PHPMailer library files are included in the source code and you can install PHPMailer without composer in PHP.

SMTP Configuration:

// SMTP configuration
$mail->isSMTP();
$mail->Host     'smtp.example.com';
$mail->SMTPAuth true;
$mail->Username 'user@example.com';
$mail->Password '******';
$mail->SMTPSecure 'tls';
$mail->Port     587;

Configure Email:

// Sender info 
$mail->setFrom('sender@example.com''SenderName');
$mail->addReplyTo('reply@example.com''SenderName');

// Add a recipient
$mail->addAddress('recipient@example.com');

// Add cc or bcc 
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

// Email subject
$mail->Subject 'Send Email via SMTP using PHPMailer';

// Set email format to HTML
$mail->isHTML(true);

// Email body content
$mailContent '
    <h2>Send HTML Email using SMTP Server in PHP</h2>
    <p>It is a test email by Solution Doodz, sent via SMTP server with PHPMailer using PHP.</p>
;
$mail->Body $mailContent;

// Send email
if(!$mail->send()){
    echo 
'Message could not be sent. Mailer Error: '.$mail->ErrorInfo;
}else{
    echo 
'Message has been sent.';
}

Send HTML Email with Attachments

// Add attachments
$mail->addAttachment('files/demo.pdf');
$mail->addAttachment('files/demo.docx');
$mail->addAttachment('images/demo.png''new-name.png'); //set new name

Send Email to Multiple Recipients

// Add multiple recipients
$mail->addAddress('dixit@gmail.com''Dixit Patel');
$mail->addAddress('mark@example.com'); // name is optional

Send Email using Gmail SMTP

// SMTP configuration
$mail->isSMTP();
$mail->Host     'smtp.gmail.com';
$mail->SMTPAuth true;
$mail->Username 'solutiondoodz@gmail.com';
$mail->Password '********';
$mail->SMTPSecure 'tls';
$mail->Port     587;

Send Email in localhost

// SMTP configuration
$mail->isSMTP();
$mail->Host     'localhost';
$mail->Port     25;

Post a Comment

0 Comments