Tuesday, November 5, 2024
HomeUncategorizedSend Email using PHP from SMTP Authentication with PHPMailer

Send Email using PHP from SMTP Authentication with PHPMailer

Many PHP developers utilize email in their code. The only PHP function that supports this is the mail() function. However, it does not provide any assistance for making use of popular features such as HTML-based emails and attachments.

Formatting email correctly is surprisingly difficult. There are myriad overlapping RFCs, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you’ll find online that uses the mail() function directly is just plain wrong! Please don’t be tempted to do it yourself – if you don’t use PHPMailer, there are many other excellent libraries that you should look at before rolling your own – try SwiftMailer, Zend_Mail, eZcomponents etc.

The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD and OS X platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP implementation allows email sending on Windows platforms without a local mail server.

 Step 1: Setup PHPMailer in Application:

Download PHPMailer from Github under lib/ directory of your project, you may change this location as per your need.

# wget https://github.com/PHPMailer/PHPMailer/archive/master.zip
# unzip master
# mv PHPMailer-master /path/to/project/lib/PHPMailer
                   (Example : /var/www/html/)

Step 2: Sending Test Email using PHPMailer:

Now create a simple php script sendMail.php in your web document root and add below content. Below script is using Gmail smtp server for sending mails. You may use any other SMTP server like Amazon SES, Sendgrid, Mailchimp or Mandril App etc.

<?php
require 'lib/PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@gmail.com';
$mail->Password = '_password_';
$mail->SMTPSecure = 'tls';

$mail->From = 'sender@example.com';
$mail->FromName = 'Your Name';
$mail->addAddress('recipient@example.com');

$mail->isHTML(true);

$mail->Subject = 'Test Mail Subject!';
$mail->Body    = 'This is SMTP Email Test';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
 } else {
    echo 'Message has been sent';
}
?>

Now access this application using browser with your domain name following by script name

http://example.com/sendMail.php
RELATED ARTICLES
- Advertisment -

Most Popular

Recent Comments