Отправка мыла посредством phpmail

Статус
В этой теме нельзя размещать новые ответы.

WaterSpirit

Читатель
Регистрация
16 Июл 2007
Сообщения
113
Реакции
18
Доброго времени суток.
Подскажите пожалуйста, что должно быть установлено в php, чтоб он отправлял мыла. Понять ни как не могу, не отправляют сайты сообщения на мыло, хоть убейся. Может что-то нужно дополнительно прописывать в php.ini?
Заранее Благодарю.
 
Доброго времени суток.
Подскажите пожалуйста, что должно быть установлено в php, чтоб он отправлял мыла. Понять ни как не могу, не отправляют сайты сообщения на мыло, хоть убейся. Может что-то нужно дополнительно прописывать в php.ini?
Заранее Благодарю.

Может у тебя в скрипте косяк? Щас многие почтовые службы режут корявые письма посланные через скрипт, приведи пример кода которым ты пытаешься отправлять письма.
 
Может у тебя в скрипте косяк? Щас многие почтовые службы режут корявые письма посланные через скрипт, приведи пример кода которым ты пытаешься отправлять письма.

PHP:
//------------------------------------------------
// Email class:
// Sends out emails
//------------------------------------------------
class Email
{
	//------------------------------------------------
	// Send email
	//------------------------------------------------
	function send($from_email, $from_name, $to, $subject, $body, $headers = "")
	{
		global $PREFS;

		//------------------------------------------------
		// Set new lines
		//------------------------------------------------
		if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
			$eol="\r\n";
		} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
			$eol="\r";
		} else {
			$eol="\n";
		}

		//------------------------------------------------
		// Check if this is PHP Mail
		//------------------------------------------------
		if ($PREFS->conf['mail_type'] == "mail")
		{
			if ($PREFS->conf['html_emails'])
				$format = "MIME-Version: 1.0".$eol."Content-Type: text/html;";
			else
				$format = "Content-Type: text/plain;";

			//------------------------------------------------
			// Prepare headers
			//------------------------------------------------
			$headers = "From: $from_name <$from_email>".$eol."$format charset=UTF-8".$eol."Content-Transfer-Encoding: 8bit".($headers ? $eol.$headers : '');


			//------------------------------------------------
			// Prepare body
			//------------------------------------------------
			$body = str_replace(array("\r\n", "\r", "\n"), array("\n", "\n", $eol), trim($body));


			//------------------------------------------------
			// Send email
			//------------------------------------------------
			if (@mail($to, $subject, $body, $headers))
				return 1;
			else
				return 0;
		}
		//------------------------------------------------
		// Check if this is SMTP
		//------------------------------------------------
		elseif ($PREFS->conf['mail_type'] == "smtp")
		{
			//------------------------------------------------
			// Include SMTP class
			//------------------------------------------------
			include_once SYS_PATH . 'includes/core/core.smtp.php';


			//------------------------------------------------
			// Set parameters
			//------------------------------------------------
			$params['host'] = $PREFS->conf['smtp_hostname'];
			$params['port'] = $PREFS->conf['smtp_port'];
			$params['user'] = $PREFS->conf['smtp_username'];
			$params['pass'] = $PREFS->conf['smtp_password'];


			if ($PREFS->conf['html_emails']) {
				$send_params['headers']	= array('From: "' . $from_name . '" <' . $from_email . '>',
												   'To: ' . $to,
												   'Subject: ' . $subject,
												   'MIME-Version: 1.0',
												   'Content-Type: text/html; charset=utf-8',
												   'Content-Transfer-Encoding: 8bit',
												   'Date: ' . strftime("%a, %d %b %Y %H:%M:%S %Z"));
			}
			else {
				$send_params['headers']	= array('From: "' . $from_name . '" <' . $from_email . '>',
												   'To: ' . $to,
												   'Subject: ' . $subject,
												   'Content-Type: text/plain; charset=utf-8',
												   'Content-Transfer-Encoding: 8bit',
												   'Date: ' . strftime("%a, %d %b %Y %H:%M:%S %Z"));
				$format = "Content-Type: text/plain;";
			}

			//------------------------------------------------
			// Set headers
			//------------------------------------------------
			$send_params['recipients'] = array($to);
			$send_params['from'] = $from_email;
			$send_params['body'] = "$body";

			
			//------------------------------------------------
			// Send email
			//------------------------------------------------
			if(is_object($smtp = smtp::connect($params)) AND $smtp->send($send_params))
				return 1;
			else
				return 0;
		}
	}
	// End function

}
// End class

вот так выглядит core.smtp
PHP:
/


class smtp
{
	var $authenticated;
	var $connection;
	var $recipients;
	var $headers;
	var $timeout;
	var $errors;
	var $status;
	var $body;
	var $from;
	var $host;
	var $port;
	var $helo;
	var $auth;
	var $user;
	var $pass;

	/***************************************
	** Constructor function. Arguments:
	** $params - An assoc array of parameters:
	**
	**   host	- The hostname of the smtp server		Default: localhost
	**   port	- The port the smtp server runs on		Default: 25
	**   helo	- What to send as the HELO command		Default: localhost
	**			 (typically the hostname of the
	**			 machine this script runs on)
	**   auth	- Whether to use basic authentication	Default: FALSE
	**   user	- Username for authentication			Default: <blank>
	**   pass	- Password for authentication			Default: <blank>
	**   timeout - The timeout in seconds for the call	Default: 5
	**			 to fsockopen()
	***************************************/

	function smtp($params = array()){

		if(!defined('CRLF'))
			define('CRLF', "\r\n", TRUE);

		$this->authenticated	= FALSE;
		$this->timeout			= 5;
		$this->status			= 1;
		$this->host				= 'localhost';
		$this->port				= 25;
		$this->helo				= 'localhost';
		$this->auth				= TRUE;
		$this->user				= '';
		$this->pass				= '';
		$this->errors		   = array();

		foreach($params as $key => $value){
			$this->$key = $value;
		}
	}

	/***************************************
	** Connect function. This will, when called
	** statically, create a new smtp object,
	** call the connect function (ie this function)
	** and return it. When not called statically,
	** it will connect to the server and send
	** the HELO command.
	***************************************/

	function connect($params = array()){

		if(!isset($this->status)){
			$obj = new smtp($params);
			if($obj->connect()){
				$obj->status = 2;
			}

			return $obj;

		}else{
			$this->connection = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
			if(function_exists('socket_set_timeout')){
				@socket_set_timeout($this->connection, 5, 0);
			}

			$greeting = $this->get_data();
			if(is_resource($this->connection)){
				return $this->auth ? $this->ehlo() : $this->helo();
			}else{
				$this->errors[] = 'Failed to connect to server: '.$errstr;
				return FALSE;
			}
		}
	}

	/***************************************
	** Function which handles sending the mail.
	** Arguments:
	** $params	- Optional assoc array of parameters.
	**			Can contain:
	**			  recipients - Indexed array of recipients
	**			  from	   - The from address. (used in MAIL FROM:),
	**						   this will be the return path
	**			  headers	- Indexed array of headers, one header per array entry
	**			  body	   - The body of the email
	**			It can also contain any of the parameters from the connect()
	**			function
	***************************************/

	function send($params = array()){

		foreach($params as $key => $value){
			$this->set($key, $value);
		}

		if($this->is_connected()){

			// Do we auth or not? Note the distinction between the auth variable and auth() function
			if($this->auth AND !$this->authenticated){
				if(!$this->auth())
					return FALSE;
			}

			$this->mail($this->from);
			if(is_array($this->recipients))
				foreach($this->recipients as $value)
					$this->rcpt($value);
			else
				$this->rcpt($this->recipients);

			if(!$this->data())
				return FALSE;

			// Transparency
			$headers = str_replace(CRLF.'.', CRLF.'..', trim(implode(CRLF, $this->headers)));
			$body	= str_replace(CRLF.'.', CRLF.'..', $this->body);
			$body	= $body[0] == '.' ? '.'.$body : $body;

			$this->send_data($headers);
			$this->send_data('');
			$this->send_data($body);
			$this->send_data('.');

			$result = (substr(trim($this->get_data()), 0, 3) === '250');
			//$this->rset();
			return $result;
		}else{
			$this->errors[] = 'Not connected!';
			return FALSE;
		}
	}

	/***************************************
	** Function to implement HELO cmd
	***************************************/

	function helo(){
		if(is_resource($this->connection)
				AND $this->send_data('HELO '.$this->helo)
				AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){

			return TRUE;

		}else{
			$this->errors[] = 'HELO command failed, output: ' . trim(substr(trim($error),3));
			return FALSE;
		}
	}

	/***************************************
	** Function to implement EHLO cmd
	***************************************/

	function ehlo(){
		if(is_resource($this->connection)
				AND $this->send_data('EHLO '.$this->helo)
				AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){

			return TRUE;

		}else{
			$this->errors[] = 'EHLO command failed, output: ' . trim(substr(trim($error),3));
			return FALSE;
		}
	}

	/***************************************
	** Function to implement RSET cmd
	***************************************/

	function rset(){
		if(is_resource($this->connection)
				AND $this->send_data('RSET')
				AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){

			return TRUE;

		}else{
			$this->errors[] = 'RSET command failed, output: ' . trim(substr(trim($error),3));
			return FALSE;
		}
	}

	/***************************************
	** Function to implement QUIT cmd
	***************************************/

	function quit(){
		if(is_resource($this->connection)
				AND $this->send_data('QUIT')
				AND substr(trim($error = $this->get_data()), 0, 3) === '221' ){

			@fclose($this->connection);
			$this->status = 1;
			return TRUE;

		}else{
			$this->errors[] = 'QUIT command failed, output: ' . trim(substr(trim($error),3));
			return FALSE;
		}
	}

	/***************************************
	** Function to implement AUTH cmd
	***************************************/

	function auth(){
		if(is_resource($this->connection)
				AND $this->send_data('AUTH LOGIN')
				AND substr(trim($error = $this->get_data()), 0, 3) === '334'
				AND $this->send_data(base64_encode($this->user))			// Send username
				AND substr(trim($error = $this->get_data()),0,3) === '334'
				AND $this->send_data(base64_encode($this->pass))			// Send password
				AND substr(trim($error = $this->get_data()),0,3) === '235' ){

			$this->authenticated = TRUE;
			return TRUE;

		}else{
			$this->errors[] = 'AUTH command failed: ' . trim(substr(trim($error),3));
			return FALSE;
		}
	}

	/***************************************
	** Function that handles the MAIL FROM: cmd
	***************************************/

	function mail($from){

		if($this->is_connected()
			AND $this->send_data('MAIL FROM:<'.$from.'>')
			AND substr(trim($this->get_data()), 0, 2) === '250' ){

			return TRUE;

		}else
			return FALSE;
	}

	/***************************************
	** Function that handles the RCPT TO: cmd
	***************************************/

	function rcpt($to){

		if($this->is_connected()
			AND $this->send_data('RCPT TO:<'.$to.'>')
			AND substr(trim($error = $this->get_data()), 0, 2) === '25' ){

			return TRUE;

		}else{
			$this->errors[] = trim(substr(trim($error), 3));
			return FALSE;
		}
	}

	/***************************************
	** Function that sends the DATA cmd
	***************************************/

	function data(){

		if($this->is_connected()
			AND $this->send_data('DATA')
			AND substr(trim($error = $this->get_data()), 0, 3) === '354' ){

			return TRUE;

		}else{
			$this->errors[] = trim(substr(trim($error), 3));
			return FALSE;
		}
	}

	/***************************************
	** Function to determine if this object
	** is connected to the server or not.
	***************************************/

	function is_connected(){

		return (is_resource($this->connection) AND ($this->status === 2));
	}

	/***************************************
	** Function to send a bit of data
	***************************************/

	function send_data($data){

		if(is_resource($this->connection)){
			return @fwrite($this->connection, $data.CRLF, strlen($data)+2);

		}else
			return FALSE;
	}

	/***************************************
	** Function to get data.
	***************************************/

	function &get_data(){

		$return = '';
		$line   = '';
		$loops  = 0;

		if(is_resource($this->connection)){
			while((strpos($return, CRLF) === FALSE OR substr($line,3,1) !== ' ') AND $loops < 100){
				$line	= @fgets($this->connection, 512);
				$return .= $line;
				$loops++;
			}
			return $return;

		}else
			return FALSE;
	}

	/***************************************
	** Sets a variable
	***************************************/

	function set($var, $value){

		$this->$var = $value;
		return TRUE;
	}

}
// End of class
вот так выглядит fns.validate
PHP:
//------------------------------------------------
// Validate email
//------------------------------------------------
function validate_email($email)
{
	if (strlen($email) < 4  ||  strlen($email) > 64)
		return 1;
	elseif (!preg_match("/^([a-z0-9_\-]+)(\.[a-z0-9_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i", $email))
		return 2;
	else
		return 0;
}
// End function


//------------------------------------------------
//  Validate IP Address
//------------------------------------------------
function valid_ip($ip)
{
	if (!preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/", $ip))
		return false;

	return true;
}
// End function


//------------------------------------------------
// Validate username
//------------------------------------------------
function validate_username($name, $min = 4, $max = 32)
{
	if (strlen($name) < $min  ||  strlen($name) > $max)
		return 1;
	elseif (preg_match('/[^_a-zA-Z0-9]+/', $name))
		return 2;
	//elseif (preg_match('/[\"\\\'\<\>\-\!\$\@\%\^\#\&\*\(\)\~\`\=\[\]\;\:\/\\n\\t\.\,\?\!]+/', $name))
	//	return 2;
	elseif (preg_match('/[\"\\\'\<\>\-\!\$\@\%\^\#\&\*\(\)\~\`\=\[\]\;\:\/\\n\\t\.\,\?\!]+/', $name))
		return 2;
	elseif (preg_match('/^(\d+|[\W_]+|_+)$/', $name) )
		return 3;
	else
		return 0;
}
// End function


//------------------------------------------------
// Validate email
//------------------------------------------------
function validate_password($password, $min = 4, $max = 32)
{
	if (strlen($password) < $min  ||  strlen($password) > $max)
		return 1;
	elseif (preg_match("/[^_a-zA-Z0-9]+/", $password))
		return 2;
	else
		return 0;
}
// End function


//------------------------------------------------
// Validate hash
//------------------------------------------------
function validate_hash($hash, $length = 32)
{
	if (strlen($hash) != $length)
		return 1;
	elseif (preg_match("/[^a-zA-Z0-9]+/", $hash))
		return 2;
	else
		return 0;
}
// End function
Вот так выглядит напоминание пароля через мыло
PHP:
//------------------------------------------------
// Includes
//------------------------------------------------
include SYS_PATH . 'includes/languages/' . SYS_LANG . '/lang.lib.account_lostpass.php';
include SYS_PATH . 'includes/core/core.email.php';
include SYS_PATH . 'includes/fns/fns.validate.php';


//------------------------------------------------
// Check if the user is logged in
//------------------------------------------------
if ($SESSION->auth)
	redirect(VIR_PATH);


//------------------------------------------------
// Resend hash
//------------------------------------------------
show_resendhash();


//------------------------------------------------
// Resend hash
//------------------------------------------------
function show_resendhash()
{
	global $DB, $LANG, $TEMPLATE, $SESSION, $PREFS;


	//------------------------------------------------
	// Set template file
	//------------------------------------------------
	$TEMPLATE->set_template("account_sendhash.tpl");


	//------------------------------------------------
	// Assign page title
	//------------------------------------------------
	$TEMPLATE->assign('app_page', ($LANG['forgotpassword']['app_resendhash']));


	//------------------------------------------------
	// Set default values
	//------------------------------------------------
	$username = isset($_POST['username']) && $_POST['username'] ? $DB->strip_slashes(trim($_POST['username'])) : "";
	$email	= isset($_POST['email'])	&& $_POST['email']	? $DB->strip_slashes(trim($_POST['email']))	: "";


	//------------------------------------------------
	// Check if the user has clicked on Submit
	//------------------------------------------------
	if ( isset($_POST['losthash'])  &&  $_POST['losthash'] ) {
		do_resendhash($username, $email);
	}


	//------------------------------------------------
	// Assign template vars
	//------------------------------------------------
	$TEMPLATE->assign("username", htmlentities2utf8($username));
	$TEMPLATE->assign("email",	htmlentities2utf8($email));


	return 1;
}
// End Function


//------------------------------------------------
// Send hash
//------------------------------------------------
function do_resendhash($username, $email)
{
	global $DB, $LANG, $TEMPLATE, $PREFS;


	// *system demo admin label* //
	//------------------------------------------------
	// Validate username
	//------------------------------------------------
	if ( ($username == ""  &&  $email == "") || ($PREFS->conf['lostpass_username_email'] == 'both' && ($username == ""  ||  $email == "")) )
	{
		$TEMPLATE->set_message("error", ($LANG['forgotpassword']['invalid_input']), 0, 0);
		return 0;
	}


	//------------------------------------------------
	// Validate username
	//------------------------------------------------
	if ($username != "")
	{
		$valid_username = validate_username($username, $PREFS->conf['min_username_length']);
		if ($valid_username == 1)
		{
			$TEMPLATE->set_message("error", str_replace("%1%", $PREFS->conf['min_username_length'], ($LANG['forgotpassword']['username_too_long'])), 0, 0);
			return 0;
		}
		elseif ($valid_username == 2 || $valid_username == 3)
		{
			$TEMPLATE->set_message("error", ($LANG['forgotpassword']['invalid_username']), 0, 0);
			return 0;
		}
	}


	//------------------------------------------------
	// Validate email
	//------------------------------------------------
	if ($email != "")
	{
		$valid_email =  validate_email($email);
		if ($valid_email  == 1)
		{
			$TEMPLATE->set_message("error", str_replace("%1%", 4, ($LANG['forgotpassword']['email_too_long'])), 0, 0);
			return 0;
		}
		elseif ($valid_email == 2)
		{
			$TEMPLATE->set_message("error", ($LANG['forgotpassword']['invalid_email']), 0, 0);
			return 0;
		}
	}



	//------------------------------------------------
	// Convert username to lower case
	//------------------------------------------------
	$username = mysql_real_escape_string($username);
	$email = mysql_real_escape_string($email);


	//------------------------------------------------
	// Where clause
	//------------------------------------------------
	$where = array();
	if ($username) {
		$where[] = "username='$username'";
	}
	if ($email) {
		$where[] = "email='$email'";
	}
	$where = implode(($PREFS->conf['lostpass_username_email'] == 'both' ? ' AND ' : ' OR '), $where);


	//------------------------------------------------
	// Get member info
	//------------------------------------------------
	$result = $DB->query("SELECT member_id, group_id, username, email, active FROM " . DB_PREFIX . "members WHERE ($where) AND group_id!=" . $PREFS->conf['canceled_member_group'] . " LIMIT 1");


	//------------------------------------------------
	// Check if resultset contains rows
	//------------------------------------------------
	if ($DB->num_rows($result) == 1)
	{
		//------------------------------------------------
		// Fetch result set
		//------------------------------------------------
		$obj = $DB->fetch_object($result);


		if ( $obj->group_id != $PREFS->conf['pending_member_group'] )
		{
			$TEMPLATE->set_message("error", ($LANG['forgotpassword']['already_active']), 0, 0);
			redirect(VIR_PATH . ($PREFS->conf['fancy_urls'] ? "account/login/" : "index.php?m=account_login"));
		}
		elseif ($PREFS->conf['activation_type'] != 3)
		{
			//------------------------------------------------
			// Set values
			//------------------------------------------------
			$member_id  = $obj->member_id;
			$email	  = $obj->email;
			$username = $obj->username;
			$hash	   = random_string(32, 0);
			$DB->query("UPDATE " . DB_PREFIX . "members SET sessionhash='".mysql_real_escape_string($hash)."' WHERE member_id=$member_id LIMIT 1");
		}
		else
		{
			//------------------------------------------------
			// Set message
			//------------------------------------------------
			$TEMPLATE->set_message("error", ($LANG['forgotpassword']['invalid_username_email']), 0, 0);
			return 0;
		}
	}
	else
	{
		//------------------------------------------------
		// Set message
		//------------------------------------------------
		$TEMPLATE->set_message("error", ($LANG['forgotpassword']['invalid_username_email']), 0, 0);
		return 0;
	}


	//------------------------------------------------
	// Clean up
	//------------------------------------------------
	unset($obj);
	unset($result);


	//--------------------------------------------
	// Get email templates
	//--------------------------------------------
	$PREFS->get_email_templates(array('member_activation_instructions'));


	//------------------------------------------------
	// Create email class
	//------------------------------------------------
	$EMAIL = new Email();


	//------------------------------------------------
	// Replace email body with tagged values
	$PREFS->conf['member_activation_instructions_body'] = str_replace("{username}",   $username,   $PREFS->conf['member_activation_instructions_body']);
	$PREFS->conf['member_activation_instructions_body'] = str_replace("{password}",   "*hidden*",   $PREFS->conf['member_activation_instructions_body']);
	$PREFS->conf['member_activation_instructions_body'] = str_replace("{email}",	  $email,	  $PREFS->conf['member_activation_instructions_body']);
	$PREFS->conf['member_activation_instructions_body'] = str_replace("{hash}",	   $hash,$PREFS->conf['member_activation_instructions_body']);
	$PREFS->conf['member_activation_instructions_body'] = str_replace("{website}",	VIR_PATH, $PREFS->conf['member_activation_instructions_body']);
	$PREFS->conf['member_activation_instructions_body'] = str_replace("{activation_link}", VIR_PATH . ($PREFS->conf['fancy_urls'] ? "account/activate/$member_id/$hash/" : "index.php?m=account_activate&id=$member_id&hash=$hash&a=1"), $PREFS->conf['member_activation_instructions_body']);

	//------------------------------------------------
	// Send out an email to the member
	//------------------------------------------------
	$EMAIL->send($PREFS->conf['return_email'], $PREFS->conf['return_email_name'], $email, $PREFS->conf['member_activation_instructions_subject'], $PREFS->conf['member_activation_instructions_body']);


	//------------------------------------------------
	// Set the message
	//------------------------------------------------
	$TEMPLATE->set_message("info", ($LANG['forgotpassword']['hash_resent']), 0, 0);
	redirect(VIR_PATH . ($PREFS->conf['fancy_urls'] ? "account/login/" : "index.php?m=account_login"));


	return 1;
}
// End Function
Больше про мыло ни где не упоминается. Самое интересное, что в настройках прописываю либо smtp либо phpmail. Но они оба не работают :(
 
Попробуй на простом скрипте
Код:
<?php
mail("to@gmail.com", "the subject", "message",
     "From: from@gmail.com \r\n"
    ."X-Mailer: PHP/" . phpversion());
?>

Но мне кажется дело в хостере. Напиши ему.
 
Пробуешь у хостера или дома на каких-то "денверах"?
 
Пробуешь у хостера или дома на каких-то "денверах"?

На арендованном серваке, с другого сайта на этом же серваке отправляется, а этот падла не хочет. Вообще это подтверждение реги.
 
Смотри лог ошибок.
 
На арендованном серваке, с другого сайта на этом же серваке отправляется, а этот падла не хочет. Вообще это подтверждение реги.

Если сервак арендованный, посмотри запущенна и работает ли у тебя Sendmail или qmail, посмотри их Логи.

Если запущена, то смотри php.ini правильна ли она там прописанна.

А вобще лучше всего на примере простого скрипта включить чтобы отображались все ошибки , и сразу увидишь на каком месте косяк.

И потом это должны быть проблемы суппорта...
 
WaterSpirit если у Вас скрипт выполняется и нигде никаких ошибок не вылазеет, так может быть письма просто не доходят.
И еще если совсем никак не получается то письма можно послать и прямой отправкой в порт. Но это уже извращения из разряда переписывания стандартных функций.
 
Спасибо всем, буду пробовать
 
Статус
В этой теме нельзя размещать новые ответы.
Назад
Сверху