Send E-Mails Via SMTP Server In PHP – GMail & Outlook

PHP

Read {count} times since 2020

Email Service providers have POP and SMTP servers for incoming and outgoing E-Mails. SMTP is for Outgoing (Sending) emails and POP is for Incoming (Receiving) emails. If you have an account in email services, it means that you can send or receive emails using these servers. This service is free, fast and secure. You can change the “From” address and the “From” name if you send emails using SMTP server. In this post I will tell you how to send emails using SMTP servers of GMailOutlook in PHP.

PHPMailer

We are going to use PHPMailer class for sending emails. It’s an easy usable PHP library for sending emails. This class is included in the Download File.

Configuration

This configuration contains account information, Recipient address with name and the message details :

$account="[email protected]";
$password="accountpassword";
$to="[email protected]";
$from="[email protected]";
$from_name="Vishal G.V";
$msg="<strong>This is a bold text.</strong>"; // HTML message
$subject="HTML message";

GMail

Include PHPMailer class first :

include("phpmailer/class.phpmailer.php");

Create the Class object and append the settings of the SMTP server :

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth= true;
$mail->Port = 465; // Or 587
$mail->Username= $account;
$mail->Password= $password;
$mail->SMTPSecure = 'ssl';
$mail->From = $from;
$mail->FromName= $from_name;
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->addAddress($to);

Then, check if the mail sends without error. If there is an error, it will print out the error :

if(!$mail->send()){
 echo "Mailer Error: " . $mail->ErrorInfo;
}else{
 echo "E-Mail has been sent";
}

This concludes the GMail part.

Outlook

Include PHPMailer class first :

include("phpmailer/class.phpmailer.php");

Create the Class object and append the settings of the SMTP server :

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "smtp.live.com";
$mail->SMTPAuth= true;
$mail->Port = 587;
$mail->Username= $account;
$mail->Password= $password;
$mail->SMTPSecure = 'tls';
$mail->From = $from;
$mail->FromName= $from_name;
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->addAddress($to);

Then, check if the mail sends without any errors. If there is an error, it will print out the error :

if(!$mail->send()){
 echo "Mailer Error: " . $mail->ErrorInfo;
}else{
 echo "E-Mail has been sent";
}

If there was an error printed out and you need help, please comment.

Show Comments