How to mail using google smtp in php
To send emails using Google SMTP in PHP, you'll need to configure your PHP script to use Google's SMTP server. Here's a step-by-step guide:
Prerequisites:
- You have a Google account and have enabled the "Less secure app access" option in your account settings. This is required for PHP scripts to access your Google account.
- You have a PHP script that can send emails using SMTP.
Step 1: Configure your PHP script
In your PHP script, you'll need to set the following variables:
SMTP_HOST
: The hostname of Google's SMTP server, which issmtp.gmail.com
.SMTP_PORT
: The port number of Google's SMTP server, which is587
.SMTP_USERNAME
: Your Google account email address.SMTP_PASSWORD
: Your Google account password.FROM_EMAIL
: The email address that will be used as the sender's email address.
Here's an example of how you can set these variables:
<?php
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587);
define('SMTP_USERNAME', '[email protected]');
define('SMTP_PASSWORD', 'your_password');
define('FROM_EMAIL', '[email protected]');
?>
Step 2: Use the PHPMailer library (optional)
To simplify the process of sending emails using Google SMTP, you can use the PHPMailer library. You can download the library from the official website or install it using Composer.
Here's an example of how you can use PHPMailer to send an email:
<?php
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = SMTP_HOST;
$mail->Port = SMTP_PORT;
$mail->SMTPAuth = true;
$mail->Username = SMTP_USERNAME;
$mail->Password = SMTP_PASSWORD;
$mail->setFrom(FROM_EMAIL, 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using Google SMTP';
if (!$mail->send()) {
echo 'Error sending email: '. $mail->ErrorInfo;
} else {
echo 'Email sent successfully!';
}
?>
Step 3: Send the email
Once you've configured your PHP script and set up the email details, you can send the email using the send()
method.
Here's an example of how you can send an email using the send()
method:
<?php
$mail->send();
?>
That's it! With these steps, you should be able to send emails using Google SMTP in your PHP script.
Important notes:
- Make sure to replace
[email protected]
andyour_password
with your actual Google account email address and password. - Enable the "Less secure app access" option in your Google account settings to allow PHP scripts to access your account.
- Be aware that using Google SMTP may have limitations, such as a daily email sending limit.