Jump to content

Complicated SMTP Mail Problem


gasper000

Recommended Posts

Well, I am a php beginner trying to develop a php form which uses the confirmation email process as a validation technique. I tried editing php.ini, downloaded pear, tried different servers but everytime I end with having an error sending the confirmation email. I used Yahoo, Google, & AOL servers.

 

I will explain the google trial as I tested sending an email using Outlook Express using these settings & it was a successful trial.

 

Server details

Name: Google

SMTP Server: smtp.google.com

Port: 465

 

php.ini Configuration

[mail function]

For Win32 only.

SMTP = smtp.google.com

smtp_port = 465

 

Pear Settings

smtp.php

<?php

/** Error: Failed to create a Net_SMTP object */

define('PEAR_MAIL_SMTP_ERROR_CREATE', 10000);

 

/** Error: Failed to connect to SMTP server */

define('PEAR_MAIL_SMTP_ERROR_CONNECT', 10001);

 

/** Error: SMTP authentication failure */

define('PEAR_MAIL_SMTP_ERROR_AUTH', 10002);

 

/** Error: No From: address has been provided */

define('PEAR_MAIL_SMTP_ERROR_FROM', 10003);

 

/** Error: Failed to set sender */

define('PEAR_MAIL_SMTP_ERROR_SENDER', 10004);

 

/** Error: Failed to add recipient */

define('PEAR_MAIL_SMTP_ERROR_RECIPIENT', 10005);

 

/** Error: Failed to send data */

define('PEAR_MAIL_SMTP_ERROR_DATA', 10006);

 

/**

* SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.

* @access public

* @package Mail

* @version $Revision: 1.28 $

*/

class Mail_smtp extends Mail {

 

    /**

    * SMTP connection object.

    *

    * @var object

    * @access private

    */

    var $_smtp = null;

 

    /**

    * The SMTP host to connect to.

    * @var string

    */

    var $host = 'smtp.gmail.com';

 

    /**

    * The port the SMTP server is on.

    * @var integer

    */

    var $port = 465;

 

    /**

    * Should SMTP authentication be used?

    *

    * This value may be set to true, false or the name of a specific

    * authentication method.

    *

    * If the value is set to true, the Net_SMTP package will attempt to use

    * the best authentication method advertised by the remote SMTP server.

    *

    * @var mixed

    */

    var $auth = true;

 

    /**

    * The username to use if the SMTP server requires authentication.

    * @var string

    */

    var $username = 'my_username_at_google_goes_here';

 

    /**

    * The password to use if the SMTP server requires authentication.

    * @var string

    */

    var $password = 'my_password';

 

    /**

    * Hostname or domain that will be sent to the remote SMTP server in the

    * HELO / EHLO message.

    *

    * @var string

    */

    var $localhost = 'smtp.gmail.com';

 

    /**

    * SMTP connection timeout value.  NULL indicates no timeout.

    *

    * @var integer

    */

    var $timeout = null;

 

    /**

    * Whether to use VERP or not. If not a boolean, the string value

    * will be used as the VERP separators.

    *

    * @var mixed boolean or string

    */

    var $verp = false;

 

    /**

    * Turn on Net_SMTP debugging?

    *

    * @var boolean $debug

    */

    var $debug = false;

 

    /**

    * Indicates whether or not the SMTP connection should persist over

    * multiple calls to the send() method.

    *

    * @var boolean

    */

    var $persist = false;

 

    /**

    * Constructor.

    *

    * Instantiates a new Mail_smtp:: object based on the parameters

    * passed in. It looks for the following parameters:

    *    host        The server to connect to. Defaults to localhost.

    *    port        The port to connect to. Defaults to 25.

    *    auth        SMTP authentication.  Defaults to none.

    *    username    The username to use for SMTP auth. No default.

    *    password    The password to use for SMTP auth. No default.

    *    localhost  The local hostname / domain. Defaults to localhost.

    *    timeout    The SMTP connection timeout. Defaults to none.

    *    verp        Whether to use VERP or not. Defaults to false.

    *    debug      Activate SMTP debug mode? Defaults to false.

    *    persist    Should the SMTP connection persist?

    *

    * If a parameter is present in the $params array, it replaces the

    * default.

    *

    * @param array Hash containing any parameters different from the

    *              defaults.

    * @access public

    */

    function Mail_smtp($params)

    {

        if (isset($params['smtp.gmail.com'])) $this->host = $params['smtp.gmail.com'];

        if (isset($params['465'])) $this->port = $params['465'];

        if (isset($params['true'])) $this->auth = $params['true'];

        if (isset($params['my_username_at_google_goes_here'])) $this->username = $params['my_username_at_google_goes_here'];

        if (isset($params['my_password'])) $this->password = $params['my_password'];

        if (isset($params['smtp.gmail.com'])) $this->localhost = $params['smtp.gmail.com'];

        if (isset($params['timeout'])) $this->timeout = $params['timeout'];

        if (isset($params['verp'])) $this->verp = $params['verp'];

        if (isset($params['debug'])) $this->debug = (boolean)$params['debug'];

        if (isset($params['persist'])) $this->persist = (boolean)$params['persist'];

 

        register_shutdown_function(array(&$this, '_Mail_smtp'));

    }

 

    /**

    * Destructor implementation to ensure that we disconnect from any

    * potentially-alive persistent SMTP connections.

    */

    function _Mail_smtp()

    {

        $this->disconnect();

    }

 

    /**

    * Implements Mail::send() function using SMTP.

    *

    * @param mixed $recipients Either a comma-seperated list of recipients

    *              (RFC822 compliant), or an array of recipients,

    *              each RFC822 valid. This may contain recipients not

    *              specified in the headers, for Bcc:, resending

    *              messages, etc.

    *

    * @param array $headers The array of headers to send with the mail, in an

    *              associative array, where the array key is the

    *              header name (e.g., 'Subject'), and the array value

    *              is the header value (e.g., 'test'). The header

    *              produced from those values would be 'Subject:

    *              test'.

    *

    * @param string $body The full text of the message body, including any

    *              Mime parts, etc.

    *

    * @return mixed Returns true on success, or a PEAR_Error

    *              containing a descriptive error message on

    *              failure.

    * @access public

    */

    function send($recipients, $headers, $body)

    {

        include_once 'Net/SMTP.php';

 

        /* If we don't already have an SMTP object, create one. */

        if (is_object($this->_smtp) === false) {

            $this->_smtp =& new Net_SMTP($this->host, $this->port,

                                        $this->localhost);

 

            /* If we still don't have an SMTP object at this point, fail. */

            if (is_object($this->_smtp) === false) {

                return PEAR::raiseError('Failed to create a Net_SMTP object',

                                        PEAR_MAIL_SMTP_ERROR_CREATE);

            }

 

            /* Configure the SMTP connection. */

            if ($this->debug) {

                $this->_smtp->setDebug(true);

            }

 

            /* Attempt to connect to the configured SMTP server. */

            if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {

                $error = $this->_error('Failed to connect to ' .

                                      $this->host . ':' . $this->port,

                                      $res);

                return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);

            }

 

            /* Attempt to authenticate if authentication has been enabled. */

            if ($this->auth) {

                $method = is_string($this->auth) ? $this->auth : '';

 

                if (PEAR::isError($res = $this->_smtp->auth($this->username,

                                                            $this->password,

                                                            $method))) {

                    $error = $this->_error("$method authentication failure",

                                          $res);

                    $this->_smtp->rset();

                    return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);

                }

            }

        }

 

        $this->_sanitizeHeaders($headers);

        $headerElements = $this->prepareHeaders($headers);

        if (PEAR::isError($headerElements)) {

            $this->_smtp->rset();

            return $headerElements;

        }

        list($from, $textHeaders) = $headerElements;

 

        /* Since few MTAs are going to allow this header to be forged

        * unless it's in the MAIL FROM: exchange, we'll use

        * Return-Path instead of From: if it's set. */

        if (!empty($headers['Return-Path'])) {

            $from = $headers['Return-Path'];

        }

 

        if (!isset($from)) {

            $this->_smtp->rset();

            return PEAR::raiseError('No From: address has been provided',

                                    PEAR_MAIL_SMTP_ERROR_FROM);

        }

 

        $args['verp'] = $this->verp;

        if (PEAR::isError($res = $this->_smtp->mailFrom($from, $args))) {

            $error = $this->_error("Failed to set sender: $from", $res);

            $this->_smtp->rset();

            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);

        }

 

        $recipients = $this->parseRecipients($recipients);

        if (PEAR::isError($recipients)) {

            $this->_smtp->rset();

            return $recipients;

        }

 

        foreach ($recipients as $recipient) {

            if (PEAR::isError($res = $this->_smtp->rcptTo($recipient))) {

                $error = $this->_error("Failed to add recipient: $recipient",

                                      $res);

                $this->_smtp->rset();

                return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);

            }

        }

 

        /* Send the message's headers and the body as SMTP data. */

        if (PEAR::isError($res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body))) {

            $error = $this->_error('Failed to send data', $res);

            $this->_smtp->rset();

            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);

        }

 

        /* If persistent connections are disabled, destroy our SMTP object. */

        if ($this->persist === false) {

            $this->disconnect();

        }

 

        return true;

    }

 

    /**

    * Disconnect and destroy the current SMTP connection.

    *

    * @return boolean True if the SMTP connection no longer exists.

    *

    * @since  1.1.9

    * @access public

    */

    function disconnect()

    {

        /* If we have an SMTP object, disconnect and destroy it. */

        if (is_object($this->_smtp) && $this->_smtp->disconnect()) {

            $this->_smtp = null;

        }

 

        /* We are disconnected if we no longer have an SMTP object. */

        return ($this->_smtp === null);

    }

 

    /**

    * Build a standardized string describing the current SMTP error.

    *

    * @param string $text  Custom string describing the error context.

    * @param object $error Reference to the current PEAR_Error object.

    *

    * @return string      A string describing the current SMTP error.

    *

    * @since  1.1.7

    * @access private

    */

    function _error($text, &$error)

    {

        /* Split the SMTP response into a code and a response string. */

        list($code, $response) = $this->_smtp->getResponse();

 

        /* Build our standardized error string. */

        $msg = $text;

        $msg .= ' [sMTP: ' . $error->getMessage();

        $msg .= " (code: $code, response: $response)]";

 

        return $msg;

    }

 

}

 

 

 

 

A Form Configuration File

config.inc.php

<?php # Script 16.3 - config.inc.php

/* This script:

* - define constants and settings

* - dictates how errors are handled

* - defines useful functions

*/

 

// Document who created this site, when,why, etc.

 

 

// ********************************** //

// ************ SETTINGS ************ //

 

// Flag variable for site status:

define('LIVE', FALSE);

 

// Admin contact address:

define('EMAIL', '[email protected]');

 

// Site URL (base for all redirections):

define ('BASE_URL','http://www.example.com');

 

// Location of the MySQL connection script:

define ('MYSQL','H:\wamp\www\a3/mysqli_connect.php');

 

// Adjust the time zone for PHP 5.1 and greater:

date_default_timezone_set ('US/Eastern');

 

// ************ SETTINGS ************ //

// ********************************** //

 

 

//******************************************//

// ************ ERROR MANAGEMENT************ //

 

// Create the error handler:

function my_error_handler ($e_number,

$e_message, $e_file, $e_line, $e_vars) {

 

// Build the error message.

$message = "<p>An error occurred in

script '$e_file' on line $e_line:

$e_message\n<br />";

 

// Add the date and time:

$message .= "Date/Time: " . date('n-j-Y

H:i:s') . "\n<br />";

 

// Append $e_vars to the $message:

$message .= "<pre>" . print_r ($e_vars,

1) . "</pre>\n</p>";

 

if (!LIVE) { // Development (print the error).

 

echo '<div id="Error">' . $message .'</div><br />';

 

} else { // Don't show the error:

// Send an email to the admin:

mail(EMAIL, 'Site Error!', $message,'From: my_username_at_google_goes_here');

 

// Only print an error message if the error isn't a notice:

if ($e_number != E_NOTICE) {

echo '<div id="Error">A system error

occurred. We apologize for the

inconvenience.</div><br />';

}

} // End of !LIVE IF.

 

} // End of my_error_handler() definition.

 

// Use my error handler.

set_error_handler ('my_error_handler');

 

// ************ ERROR MANAGEMENT************ //

// ****************************************** //

ini_set('SMTP', 'smtp.gmail.com'); // SMTP of your provider (same as in Outlook)

ini_set('sendmail_from', '[email protected]'); // Your emailaddress

?>

 

register.php

<?php # Script 16.6 - register.php

// This is the registration page for the site.

 

require_once ('includes/config.inc.php');

$page_title = 'Register';

include ('includes/header.html');

 

if (isset($_POST['submitted'])) { // Handle the form.

 

require_once (MYSQL);

 

// Trim all the incoming data:

$trimmed = array_map('trim', $_POST);

 

// Assume invalid values:

$fn = $ln = $e = $p = FALSE;

 

// Check for a first name:

if (preg_match ('/^[A-Z \'.-]{2,20}$/i',

$trimmed['first_name'])) {

$fn = mysqli_real_escape_string ($dbc,

$trimmed['first_name']);

} else {

echo '<p class="error">Please enter

your first name!</p>';

}

 

// Check for a last name:

if (preg_match ('/^[A-Z \'.-]{2,40}$/i',

$trimmed['last_name'])) {

$ln = mysqli_real_escape_string ($dbc,

$trimmed['last_name']);

} else {

echo '<p class="error">Please enter

your last name!</p>';

}

 

// Check for an email address:

if (preg_match ('/^[\w.-]+@[\w.-]+\.[AZa-z]{2,6}$/', $trimmed['email'])) {

$e = mysqli_real_escape_string ($dbc,

$trimmed['email']);

} else {

echo '<p class="error">Please enter a

valid email address!</p>';

}

 

// Check for a password and match against the confirmed password:

if (preg_match ('/^\w{4,20}$/',

$trimmed['password1']) ) {

if ($trimmed['password1'] ==

$trimmed['password2']) {

$p = mysqli_real_escape_string

($dbc, $trimmed['password1']);

} else {

echo '<p class="error">Your password did not match the confirmed password!</p>';

}

} else {

echo '<p class="error">Please enter a valid password!</p>';

}

 

if ($fn && $ln && $e && $p) { // If everything's OK...

 

// Make sure the email address is available:

 

$q = "SELECT user_id FROM users WHERE email='$e'";

$r = mysqli_query ($dbc, $q) or

trigger_error("Query: $q\n<br />MySQLError: " .

mysqli_error($dbc));

 

if (mysqli_num_rows($r) == 0) { //Available.

 

// Create the activation code:

$a = md5(uniqid(rand(), true));

 

// Add the user to the database:

$q = "INSERT INTO users (email,

pass, first_name, last_name, active,

registration_date) VALUES ('$e',

SHA1('$p'), '$fn', '$ln', '$a',

NOW() )";

$r = mysqli_query ($dbc, $q) or

trigger_error("Query: $q\n<br />MySQL

Error: " . mysqli_error($dbc));

 

if (mysqli_affected_rows($dbc) == 1)

{ // If it ran OK.

 

// Send the email:

$body = "Thank you for registering

at <whatever site>. To activate

your account, please click on this

link:\n\n";

$body .= BASE_URL . 'activate.php?

x=' . urlencode($e) . "&y=$a";

mail($trimmed['email'],

'Registration Confirmation', $body,

'From: [email protected]');

 

// Finish the page:

echo '<h3>Thank you for

registering! A confirmation email

has been sent to your address.

Please click on the link in that

email in order to activate your

account.</h3>';

include ('includes/footer.html');

// Include the HTML footer.

exit(); // Stop the page.

 

} else { // If it did not run OK.

echo '<p class="error">You could

not be registered due to a system

error. We apologize for any

inconvenience.</p>';

}

 

} else { // The email address is not available.

 

echo '<p class="error">That email

address has already been registered.

If you have forgotten your password,

use the link at right to have your

password sent to you.</p>';

}

 

} else { // If one of the data tests failed.

echo '<p class="error">Please re-enter

your passwords and try again.</p>';

}

 

mysqli_close($dbc);

 

} // End of the main Submit conditional.

?>

 

<h1>Register</h1>

<form action="register.php" method="post">

<fieldset>

 

<p><b>First Name:</b> <input type="text"

name="first_name" size="20" maxlength=

"20" value="<?php if (isset($trimmed

['first_name'])) echo $trimmed

['first_name']; ?>" /></p>

 

<p><b>Last Name:</b> <input type="text"

name="last_name" size="20" maxlength=

"40" value="<?php if (isset($trimmed

['last_name'])) echo $trimmed

['last_name']; ?>" /></p>

 

<p><b>Email Address:</b> <input

type="text" name="email" size="30"

maxlength="80" value="<?php if

(isset($trimmed['email'])) echo

$trimmed['email']; ?>" /> </p>

 

<p><b>Password:</b> <input type=

"password" name="password1" size="20"

maxlength="20" /> <small>Use only

letters, numbers, and the underscore.

Must be between 4 and 20 characters

long.</small></p>

 

<p><b>Confirm Password:</b> <input

type="password" name="password2"

size="20" maxlength="20" /></p>

</fieldset>

 

<div align="center"><input type="submit"

name="submit" value="Register" /></div>

<input type="hidden" name="submitted"

value="TRUE" />

 

</form>

 

<?php // Include the HTML footer.

include ('includes/footer.html');

?>

 

<<<<<THE ERROR MESSAGE>>>>>>

1. Fatal error: Maximum execution time of 30 seconds exceeded in E:\wamp\www\a3\htdocs\includes\config.inc.php on line 37.

 

Actually, it took about 10 minutes before displaying this message.

 

 

 

I have spent 2 weeks trying to fix this but I couldn't go any further. Do you have any ideas ?!

Link to comment
https://forums.phpfreaks.com/topic/138546-complicated-smtp-mail-problem/
Share on other sites

smtp.php

<?php
/** Error: Failed to create a Net_SMTP object */
define('PEAR_MAIL_SMTP_ERROR_CREATE', 10000);

/** Error: Failed to connect to SMTP server */
define('PEAR_MAIL_SMTP_ERROR_CONNECT', 10001);

/** Error: SMTP authentication failure */
define('PEAR_MAIL_SMTP_ERROR_AUTH', 10002);

/** Error: No From: address has been provided */
define('PEAR_MAIL_SMTP_ERROR_FROM', 10003);

/** Error: Failed to set sender */
define('PEAR_MAIL_SMTP_ERROR_SENDER', 10004);

/** Error: Failed to add recipient */
define('PEAR_MAIL_SMTP_ERROR_RECIPIENT', 10005);

/** Error: Failed to send data */
define('PEAR_MAIL_SMTP_ERROR_DATA', 10006);

/**
* SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
* @access public
* @package Mail
* @version $Revision: 1.28 $
*/
class Mail_smtp extends Mail {

    /**
     * SMTP connection object.
     *
     * @var object
     * @access private
     */
    var $_smtp = null;

    /**
     * The SMTP host to connect to.
     * @var string
     */
    var $host = 'smtp.gmail.com';

    /**
     * The port the SMTP server is on.
     * @var integer
     */
    var $port = 465;

    /**
     * Should SMTP authentication be used?
     *
     * This value may be set to true, false or the name of a specific
     * authentication method.
     *
     * If the value is set to true, the Net_SMTP package will attempt to use
     * the best authentication method advertised by the remote SMTP server.
     *
     * @var mixed
     */
    var $auth = true;

    /**
     * The username to use if the SMTP server requires authentication.
     * @var string
     */
    var $username = 'my_username_at_google_goes_here';

    /**
     * The password to use if the SMTP server requires authentication.
     * @var string
     */
    var $password = 'my_password';

    /**
     * Hostname or domain that will be sent to the remote SMTP server in the
     * HELO / EHLO message.
     *
     * @var string
     */
    var $localhost = 'smtp.gmail.com';

    /**
     * SMTP connection timeout value.  NULL indicates no timeout.
     *
     * @var integer
     */
    var $timeout = null;

    /**
     * Whether to use VERP or not. If not a boolean, the string value
     * will be used as the VERP separators.
     *
     * @var mixed boolean or string
     */
    var $verp = false;

    /**
     * Turn on Net_SMTP debugging?
     *
     * @var boolean $debug
     */
    var $debug = false;

    /**
     * Indicates whether or not the SMTP connection should persist over
     * multiple calls to the send() method.
     *
     * @var boolean
     */
    var $persist = false;

    /**
     * Constructor.
     *
     * Instantiates a new Mail_smtp:: object based on the parameters
     * passed in. It looks for the following parameters:
     *     host        The server to connect to. Defaults to localhost.
     *     port        The port to connect to. Defaults to 25.
     *     auth        SMTP authentication.  Defaults to none.
     *     username    The username to use for SMTP auth. No default.
     *     password    The password to use for SMTP auth. No default.
     *     localhost   The local hostname / domain. Defaults to localhost.
     *     timeout     The SMTP connection timeout. Defaults to none.
     *     verp        Whether to use VERP or not. Defaults to false.
     *     debug       Activate SMTP debug mode? Defaults to false.
     *     persist     Should the SMTP connection persist?
     *
     * If a parameter is present in the $params array, it replaces the
     * default.
     *
     * @param array Hash containing any parameters different from the
     *              defaults.
     * @access public
     */
    function Mail_smtp($params)
    {
        if (isset($params['smtp.gmail.com'])) $this->host = $params['smtp.gmail.com'];
        if (isset($params['465'])) $this->port = $params['465'];
        if (isset($params['true'])) $this->auth = $params['true'];
        if (isset($params['my_username_at_google_goes_here'])) $this->username = $params['my_username_at_google_goes_here'];
        if (isset($params['my_password'])) $this->password = $params['my_password'];
        if (isset($params['smtp.gmail.com'])) $this->localhost = $params['smtp.gmail.com'];
        if (isset($params['timeout'])) $this->timeout = $params['timeout'];
        if (isset($params['verp'])) $this->verp = $params['verp'];
        if (isset($params['debug'])) $this->debug = (boolean)$params['debug'];
        if (isset($params['persist'])) $this->persist = (boolean)$params['persist'];

        register_shutdown_function(array(&$this, '_Mail_smtp'));
    }

    /**
     * Destructor implementation to ensure that we disconnect from any
     * potentially-alive persistent SMTP connections.
     */
    function _Mail_smtp()
    {
        $this->disconnect();
    }

    /**
     * Implements Mail::send() function using SMTP.
     *
     * @param mixed $recipients Either a comma-seperated list of recipients
     *              (RFC822 compliant), or an array of recipients,
     *              each RFC822 valid. This may contain recipients not
     *              specified in the headers, for Bcc:, resending
     *              messages, etc.
     *
     * @param array $headers The array of headers to send with the mail, in an
     *              associative array, where the array key is the
     *              header name (e.g., 'Subject'), and the array value
     *              is the header value (e.g., 'test'). The header
     *              produced from those values would be 'Subject:
     *              test'.
     *
     * @param string $body The full text of the message body, including any
     *               Mime parts, etc.
     *
     * @return mixed Returns true on success, or a PEAR_Error
     *               containing a descriptive error message on
     *               failure.
     * @access public
     */
    function send($recipients, $headers, $body)
    {
        include_once 'Net/SMTP.php';

        /* If we don't already have an SMTP object, create one. */
        if (is_object($this->_smtp) === false) {
            $this->_smtp =& new Net_SMTP($this->host, $this->port,
                                         $this->localhost);

            /* If we still don't have an SMTP object at this point, fail. */
            if (is_object($this->_smtp) === false) {
                return PEAR::raiseError('Failed to create a Net_SMTP object',
                                        PEAR_MAIL_SMTP_ERROR_CREATE);
            }

            /* Configure the SMTP connection. */
            if ($this->debug) {
                $this->_smtp->setDebug(true);
            }

            /* Attempt to connect to the configured SMTP server. */
            if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
                $error = $this->_error('Failed to connect to ' .
                                       $this->host . ':' . $this->port,
                                       $res);
                return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
            }

            /* Attempt to authenticate if authentication has been enabled. */
            if ($this->auth) {
                $method = is_string($this->auth) ? $this->auth : '';

                if (PEAR::isError($res = $this->_smtp->auth($this->username,
                                                            $this->password,
                                                            $method))) {
                    $error = $this->_error("$method authentication failure",
                                           $res);
                    $this->_smtp->rset();
                    return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
                }
            }
        }

        $this->_sanitizeHeaders($headers);
        $headerElements = $this->prepareHeaders($headers);
        if (PEAR::isError($headerElements)) {
            $this->_smtp->rset();
            return $headerElements;
        }
        list($from, $textHeaders) = $headerElements;

        /* Since few MTAs are going to allow this header to be forged
         * unless it's in the MAIL FROM: exchange, we'll use
         * Return-Path instead of From: if it's set. */
        if (!empty($headers['Return-Path'])) {
            $from = $headers['Return-Path'];
        }

        if (!isset($from)) {
            $this->_smtp->rset();
            return PEAR::raiseError('No From: address has been provided',
                                    PEAR_MAIL_SMTP_ERROR_FROM);
        }

        $args['verp'] = $this->verp;
        if (PEAR::isError($res = $this->_smtp->mailFrom($from, $args))) {
            $error = $this->_error("Failed to set sender: $from", $res);
            $this->_smtp->rset();
            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
        }

        $recipients = $this->parseRecipients($recipients);
        if (PEAR::isError($recipients)) {
            $this->_smtp->rset();
            return $recipients;
        }

        foreach ($recipients as $recipient) {
            if (PEAR::isError($res = $this->_smtp->rcptTo($recipient))) {
                $error = $this->_error("Failed to add recipient: $recipient",
                                       $res);
                $this->_smtp->rset();
                return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
            }
        }

        /* Send the message's headers and the body as SMTP data. */
        if (PEAR::isError($res = $this->_smtp->data($textHeaders . "\r\n\r\n" . $body))) {
            $error = $this->_error('Failed to send data', $res);
            $this->_smtp->rset();
            return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
        }

        /* If persistent connections are disabled, destroy our SMTP object. */
        if ($this->persist === false) {
            $this->disconnect();
        }

        return true;
    }

    /**
     * Disconnect and destroy the current SMTP connection.
     *
     * @return boolean True if the SMTP connection no longer exists.
     *
     * @since  1.1.9
     * @access public
     */
    function disconnect()
    {
        /* If we have an SMTP object, disconnect and destroy it. */
        if (is_object($this->_smtp) && $this->_smtp->disconnect()) {
            $this->_smtp = null;
        }

        /* We are disconnected if we no longer have an SMTP object. */
        return ($this->_smtp === null);
    }

    /**
     * Build a standardized string describing the current SMTP error.
     *
     * @param string $text  Custom string describing the error context.
     * @param object $error Reference to the current PEAR_Error object.
     *
     * @return string       A string describing the current SMTP error.
     *
     * @since  1.1.7
     * @access private
     */
    function _error($text, &$error)
    {
        /* Split the SMTP response into a code and a response string. */
        list($code, $response) = $this->_smtp->getResponse();

        /* Build our standardized error string. */
        $msg = $text;
        $msg .= ' [sMTP: ' . $error->getMessage();
        $msg .= " (code: $code, response: $response)]";

        return $msg;
    }

}

 

 

config.inc.php

<?php # Script 16.3 - config.inc.php
/* This script:
* - define constants and settings
* - dictates how errors are handled
* - defines useful functions
*/

// Document who created this site, when,why, etc.


// ********************************** //
// ************ SETTINGS ************ //

// Flag variable for site status:
define('LIVE', FALSE);

// Admin contact address:
define('EMAIL', '[email protected]');

// Site URL (base for all redirections):
define ('BASE_URL','http://www.example.com');

// Location of the MySQL connection script:
define ('MYSQL','H:\wamp\www\a3/mysqli_connect.php');

// Adjust the time zone for PHP 5.1 and greater:
date_default_timezone_set ('US/Eastern');

// ************ SETTINGS ************ //
// ********************************** //


//******************************************//
// ************ ERROR MANAGEMENT************ //

// Create the error handler:
function my_error_handler ($e_number,
$e_message, $e_file, $e_line, $e_vars) {

// Build the error message.
$message = "<p>An error occurred in
script '$e_file' on line $e_line:
$e_message\n<br />";

// Add the date and time:
$message .= "Date/Time: " . date('n-j-Y
H:i:s') . "\n<br />";

// Append $e_vars to the $message:
$message .= "<pre>" . print_r ($e_vars,
1) . "</pre>\n</p>";

if (!LIVE) { // Development (print the error).

echo '<div id="Error">' . $message .'</div><br />';

} else { // Don't show the error:
// Send an email to the admin:
mail(EMAIL, 'Site Error!', $message,'From: my_username_at_google_goes_here');

// Only print an error message if the error isn't a notice:
if ($e_number != E_NOTICE) {
echo '<div id="Error">A system error
occurred. We apologize for the
inconvenience.</div><br />';
}
} // End of !LIVE IF.

} // End of my_error_handler() definition.

// Use my error handler.
set_error_handler ('my_error_handler');

// ************ ERROR MANAGEMENT************ //
// ****************************************** //
ini_set('SMTP', 'smtp.gmail.com'); // SMTP of your provider (same as in Outlook)
ini_set('sendmail_from', '[email protected]'); // Your emailaddress
?>

 

 

register.php

<?php # Script 16.6 - register.php
// This is the registration page for the site.

require_once ('includes/config.inc.php');
$page_title = 'Register';
include ('includes/header.html');

if (isset($_POST['submitted'])) { // Handle the form.

require_once (MYSQL);

// Trim all the incoming data:
$trimmed = array_map('trim', $_POST);

// Assume invalid values:
$fn = $ln = $e = $p = FALSE;

// Check for a first name:
if (preg_match ('/^[A-Z \'.-]{2,20}$/i',
$trimmed['first_name'])) {
$fn = mysqli_real_escape_string ($dbc,
$trimmed['first_name']);
} else {
echo '<p class="error">Please enter
your first name!</p>';
}

// Check for a last name:
if (preg_match ('/^[A-Z \'.-]{2,40}$/i',
$trimmed['last_name'])) {
$ln = mysqli_real_escape_string ($dbc,
$trimmed['last_name']);
} else {
echo '<p class="error">Please enter
your last name!</p>';
}

// Check for an email address:
if (preg_match ('/^[\w.-]+@[\w.-]+\.[AZa-z]{2,6}$/', $trimmed['email'])) {
$e = mysqli_real_escape_string ($dbc,
$trimmed['email']);
} else {
echo '<p class="error">Please enter a
valid email address!</p>';
}

// Check for a password and match against the confirmed password:
if (preg_match ('/^\w{4,20}$/',
$trimmed['password1']) ) {
if ($trimmed['password1'] ==
$trimmed['password2']) {
$p = mysqli_real_escape_string
($dbc, $trimmed['password1']);
} else {
echo '<p class="error">Your password did not match the confirmed password!</p>';
}
} else {
echo '<p class="error">Please enter a valid password!</p>';
}

if ($fn && $ln && $e && $p) { // If everything's OK...

// Make sure the email address is available:

$q = "SELECT user_id FROM users WHERE email='$e'";
$r = mysqli_query ($dbc, $q) or
trigger_error("Query: $q\n<br />MySQLError: " .
mysqli_error($dbc));

if (mysqli_num_rows($r) == 0) { //Available.

// Create the activation code:
$a = md5(uniqid(rand(), true));

// Add the user to the database:
$q = "INSERT INTO users (email,
pass, first_name, last_name, active,
registration_date) VALUES ('$e',
SHA1('$p'), '$fn', '$ln', '$a',
NOW() )";
$r = mysqli_query ($dbc, $q) or
trigger_error("Query: $q\n<br />MySQL
Error: " . mysqli_error($dbc));

if (mysqli_affected_rows($dbc) == 1)
{ // If it ran OK.

// Send the email:
$body = "Thank you for registering
at <whatever site>. To activate
your account, please click on this
link:\n\n";
$body .= BASE_URL . 'activate.php?
x=' . urlencode($e) . "&y=$a";
mail($trimmed['email'],
'Registration Confirmation', $body,
'From: [email protected]');

// Finish the page:
echo '<h3>Thank you for
registering! A confirmation email
has been sent to your address.
Please click on the link in that
email in order to activate your
account.</h3>';
include ('includes/footer.html');
// Include the HTML footer.
exit(); // Stop the page.

} else { // If it did not run OK.
echo '<p class="error">You could
not be registered due to a system
error. We apologize for any
inconvenience.</p>';
}

} else { // The email address is not available.

echo '<p class="error">That email
address has already been registered.
If you have forgotten your password,
use the link at right to have your
password sent to you.</p>';
}

} else { // If one of the data tests failed.
echo '<p class="error">Please re-enter
your passwords and try again.</p>';
}

mysqli_close($dbc);

} // End of the main Submit conditional.
?>

<h1>Register</h1>
<form action="register.php" method="post">
<fieldset>

<p><b>First Name:</b> <input type="text"
name="first_name" size="20" maxlength=
"20" value="<?php if (isset($trimmed
['first_name'])) echo $trimmed
['first_name']; ?>" /></p>

<p><b>Last Name:</b> <input type="text"
name="last_name" size="20" maxlength=
"40" value="<?php if (isset($trimmed
['last_name'])) echo $trimmed
['last_name']; ?>" /></p>

<p><b>Email Address:</b> <input
type="text" name="email" size="30"
maxlength="80" value="<?php if
(isset($trimmed['email'])) echo
$trimmed['email']; ?>" /> </p>

<p><b>Password:</b> <input type=
"password" name="password1" size="20"
maxlength="20" /> <small>Use only
letters, numbers, and the underscore.
Must be between 4 and 20 characters
long.</small></p>

<p><b>Confirm Password:</b> <input
type="password" name="password2"
size="20" maxlength="20" /></p>
</fieldset>

<div align="center"><input type="submit"
name="submit" value="Register" /></div>
<input type="hidden" name="submitted"
value="TRUE" />

</form>

<?php // Include the HTML footer.
include ('includes/footer.html');
?>

 

Hey gasper000,

 

Not sure if this will help, but when I do more complex mailing I like to use the free 'swift' mailer libraries http://www.swiftmailer.org/. They have really amazing functionality and very good easy to understand documentation. It worked like a charm every time I've used it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.