Send email using PHP Script with Gmail SMTP Authentication
All the programming languages provides functions for sending emails. PHP also provides mail() function to send emails. You can use the PHP mail() function to send an email with PHP. The simplest way to do this is to send a text email. This is one way to handle sending you the results when a visitor to your website fills out a form.
Some time you require to check smtp email authentication are working with your PHP or not then follow below steps it will help you to check the email service.
Step 1: Download and Extract PHPMailer Library:
Download PHPMailer under your project or /var/www/html, you may change this location as per your need. Follow below step to download and extract PHPMailer:
# cd /var/www/html # wget http://download.techoism.com/PHPmailer.zip # unzip PHPMailer.zip # mv PHPMailer-master /var/www/html/PHPMailer
Step 2: Create sendmail.php file:
Now create an simple sendmail.php script web document root or /var/www/html and add below content.
# vim sendmail.php
<?php function Send_Mail($to,$subject,$body) { require '/var/www/html/PHPmailer/class.phpmailer.php'; $from = "from@techoism.com"; $mail = new PHPMailer(); $mail->IsSMTP(true); // SMTP $mail->SMTPAuth = true; // SMTP authentication $mail->Host= "smtp.gmail.com"; $mail->SMTPSecure = 'tls'; $mail->Username = "username@techoism.com"; // SMTP Username $mail->Password = "password"; // SMTP Password $mail->SetFrom($from, 'Dennis R'); $mail->AddReplyTo($from,'Technical Support'); $mail->Subject = $subject; $mail->MsgHTML($body); $address = $to; $mail->AddAddress($address, $to); if(!$mail->Send()) return false; else return true; } ?>
Note: If you want to enable debug mode using php script then add following entry in sendmail.php file:
# vim /var/www/html/sendmail.php
$mail->SMTPDebug = 2;
Step 3: Create index.php file:
Here called sendmail function and passing to, subject and body values. Now create an simple index.php script in web document root or /var/www/html and add below content.
# vim index.php
<?php require '/var/www/html/sendmail.php'; $to = "to@gmail.com"; $subject = "Test Mail Subject"; $body = "Hi
Email service is working
Techoism"; // HTML tags Send_Mail($to,$subject,$body); ?>
Step 4: Run PHP script:
Now access this application using browser with your domain name following by script name
http://techoism.com/index.php
Note: You can run script from command line also.
# php index.php
Thanks for the guide. I had to change a minor thing but I use this now and it makes more sense using this script as it is to have postfix forward all mail to gmail smtp’s. I’m doing some tests at the moment and it looks like I got it all in working order so thanks for the guide and mostly for giving me the idea of using php to send mails.
Grtz