Send an Email using SMTP Server and PHPMailer
Sending emails are very important in all web applications. When comes to PHP we have mail() function to send email in PHP. When you using mail() function the
mail sending from your web server. But I would say it is not very reliable using PHP native mail function. So what is the solution?. Using an SMTP server will solve
this issue of email delivery. Nowadays SMTP is most recommended solution to send email in PHP.
When you send an email using SMTP, the mail is sending from Mail server rather than the web server. Mail servers are dedicated platforms to sending/receiving emails when comparing to the normal web server.
PHPMailer is one of the most popular open source PHP libraries to send emails using PHP. After release in 2001, it became PHP developer’s favorite tool for sending email in PHP.
How to send an Email using SMTP Server and PHPMailer
You can install PHPMailer using composer or you can download the link by clicking here
composer require phpmailer/phpmailer
Sending Email from SMTP server using PHPMailer
Use the below script to send email using PHPMailer and SMTP.
You can use the mail server of an another host to send email, but for this, you first need to have authentication.
For example, I will be using my Gmail SMTP server to send email, but you need to have a Gmail account.
You don’t need a local mail server to run the code as you are using Gmail’s SMTP server to send emails.
- $mail->Host = ‘smtp.gmail.com’; – Setting Gmail SMTP Server
- $mail->SMTPAuth = true; – Enable SMTP authentication
- $mail->Username = ‘firstname.lastname@example.org’; – SMTP username, will be your Gamil username
- $mail->Password = ‘intogteldir123#’; – SMTP password, will be Gmail password
- $mail->SMTPSecure = ‘tls’; – Enable TLS encryption,
- $mail->Port = 587;
Normal cases this is enough to get working. But when you use Gmail’s SMTP settings, you have to set this truseted app in Gmail control panel.
- Login to your Gmail account
- Go to the My Account page. Click the Signing into Google link from Sign-in & security section
- Scroll down the Password & sign-in method section and turn Off the 2-Step Verification.
- Scroll down the Connected apps & sites section and turn On Allow less secure apps.
You are ready to send your email using SMTP Server.