Knowledgebase:
SMTP class function with authentication in PHP code
Posted by Tarak D, Last modified by Tarak D on 29 July 2014 06:19 PM

 

First you need to make sure the email address you will be sending from have been created for your account in your control panel i.e cPanel

 

<?php

include('Mail.php');

$recipients = 'you@yourdomain.com'; //CHANGE

$headers['From']    = 'you@yourdomain.com'; //CHANGE
$headers['To']      = 'you@yourdomain.com'; //CHANGE
$headers['Subject'] = 'Test message';

$body = 'Test message';

// Define SMTP Parameters

$params['host'] = 'mail.yourdomain.com';
$params['port'] = '25';
$params['auth'] = 'PLAIN';
$params['username'] = 'USERNAME@DOMAIN.COM'; //CHANGE
$params['password'] = 'PASSWORD'; //CHANGE

/* The following option enables SMTP debugging and will print the SMTP
conversation to the page, it will only help with authentication issues. */

$params['debug'] = 'true';

// Create the mail object using the Mail::factory method

$mail_object =& Mail::factory('smtp', $params);

// Print the parameters you are using to the page

foreach ($params as $p){
        echo "$p<br />";
}

// Send the message

$mail_object->send($recipients, $headers, $body);
?>

 

Change the following lines:

- $recipients to your email address

- $headers['From'] to your email address

- $headers['To'] to your email address

- 'USERNAME' to your email account username

- 'PASSWORD' to your email account password

  • Save the file to your web server.
  • Open a web browser and view the uploaded php file on the Internet.
  • You should see a list of the parameters you have entered and the SMTP conversation, if it was successful you will see at the end of the conversation a section that reads 'Message accepted for delivery'
  • This means that this code can be used from your web server and you can continue to integrate this into your form / application.
  • We recommend that when you do, you store the username and password variable definitions in a separate PHP file outside your public web directory and reference back to it. Storing them in a public PHP file is a potential security risk.
  • (12 vote(s))
    Helpful
    Not helpful

    Comments (0)
    Post a new comment
     
     
    Full Name:
    Email:
    Comments: