PHPMailer: Sending Emails via Gmail SMTP Server
2 min readJan 26, 2021
This example shows how to generate app credentials in Google account and settings for PHPMailer to use when sending via Google’s Gmail servers.
1. Creating credentials in your Gmail account
Login to your Google account which you are going to use for sending emails
Your account should have 2-Step Verification enabled. If it doesn’t click here to get it.
Create App passwords in Manage your Google Account > Security
Sign in, if required
- Under “Select the app and device you want to generate the app password for.” click Select app > Mail
- In Select device select Other (Custom name)
- Type a name for the app
- Click Generate
- Copy and paste somewhere the 16 character password generated, you’ll need it later
2. Setting up PHPMailer for sending via Google’s Gmail servers
//Create a new PHPMailer instance
$mail = new PHPMailer();//Tell PHPMailer to use SMTP
$mail->isSMTP();//Enable SMTP debugging. SMTP::DEBUG_SERVER = client and server messages - uncomment this if you are debugging
//$mail->SMTPDebug = SMTP::DEBUG_SERVER;//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;//Set the encryption mechanism to use - STARTTLS or SMTPS
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Whether to use SMTP authentication
$mail->SMTPAuth = true; //Username to use for SMTP authentication - use full email address for gmail account you created credentials earlier
$mail->Username = 'username@gmail.com';//Password to use for SMTP authentication - the 16 character password generated you copied before (no brakes)
$mail->Password = 'mhmrblznijnkeiqk';//Set who the message is to be sent from. If you want to use different email address as sentFrom, then you need to add the email in gmail settings > Accounts and import > Send mail as
$mail->setFrom('from@example.com', 'First-name Last-name');