Что означает php mail error

Php return mail error (PHP 4, PHP 5, PHP 7, PHP 8) mail — Send mail Description Parameters Receiver, or receivers of the mail. The formatting of this string must comply with » RFC 2822. Some examples are: user@example.com user@example.com, anotheruser@example.com User User , Another User Subject of the email to be sent. Subject […]

Содержание

  1. Php return mail error
  2. Description
  3. Parameters
  4. Return Values
  5. Changelog
  6. Examples
  7. mail — Отправляет электронную почту
  8. Описание
  9. Список параметров
  10. Возвращаемые значения
  11. Список изменений
  12. Примеры
  13. Предопределённые константы
  14. User Contributed Notes 20 notes

Php return mail error

(PHP 4, PHP 5, PHP 7, PHP 8)

mail — Send mail

Description

Parameters

Receiver, or receivers of the mail.

The formatting of this string must comply with » RFC 2822. Some examples are:

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User
  • User , Another User

Subject of the email to be sent.

Subject must satisfy » RFC 2047.

Message to be sent.

Each line should be separated with a CRLF (rn). Lines should not be larger than 70 characters.

(Windows only) When PHP is talking to a SMTP server directly, if a full stop is found on the start of a line, it is removed. To counter-act this, replace these occurrences with a double dot.

String or array to be inserted at the end of the email header.

This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (rn). If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

If an array is passed, its keys are the header names and its values are the respective header values.

Before PHP 5.4.42 and 5.5.27, repectively, additional_headers did not have mail header injection protection. Therefore, users must make sure specified headers are safe and contains headers only. i.e. Never start mail body by putting multiple newlines.

When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini .

Failing to do this will result in an error message similar to Warning: mail(): «sendmail_from» not set in php.ini or custom «From:» header missing . The From header sets also Return-Path when sending directly via SMTP (Windows only).

If messages are not received, try using a LF (n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

The additional_params parameter can be used to pass additional flags as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option.

This parameter is escaped by escapeshellcmd() internally to prevent command execution. escapeshellcmd() prevents command execution, but allows to add additional parameters. For security reasons, it is recommended for the user to sanitize this parameter to avoid adding unwanted parameters to the shell command.

Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. mail() can not allow such characters, so in programs where the use of such characters is required, alternative means of sending emails (such as using a framework or a library) is recommended.

The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a ‘X-Warning’ header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users .

Return Values

Returns true if the mail was successfully accepted for delivery, false otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

Changelog

Version Description
7.2.0 The additional_headers parameter now also accepts an array .

Examples

Example #1 Sending mail.

Using mail() to send a simple email:

// The message
$message = «Line 1rnLine 2rnLine 3» ;

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap ( $message , 70 , «rn» );

// Send
mail ( ‘caffeinated@example.com’ , ‘My Subject’ , $message );
?>

Example #2 Sending mail with extra headers.

The addition of basic headers, telling the MUA the From and Reply-To addresses:

= ‘nobody@example.com’ ;
$subject = ‘the subject’ ;
$message = ‘hello’ ;
$headers = ‘From: webmaster@example.com’ . «rn» .
‘Reply-To: webmaster@example.com’ . «rn» .
‘X-Mailer: PHP/’ . phpversion ();

mail ( $to , $subject , $message , $headers );
?>

Example #3 Sending mail with extra headers as array

This example sends the same mail as the example immediately above, but passes the additional headers as array (available as of PHP 7.2.0).

= ‘nobody@example.com’ ;
$subject = ‘the subject’ ;
$message = ‘hello’ ;
$headers = array(
‘From’ => ‘webmaster@example.com’ ,
‘Reply-To’ => ‘webmaster@example.com’ ,
‘X-Mailer’ => ‘PHP/’ . phpversion ()
);

mail ( $to , $subject , $message , $headers );
?>

Example #4 Sending mail with an additional command line parameter.

The additional_params parameter can be used to pass an additional parameter to the program configured to use when sending mail using the sendmail_path .

Example #5 Sending HTML email

It is also possible to send HTML email with mail() .

// Multiple recipients
$to = ‘johny@example.com, sally@example.com’ ; // note the comma

// Subject
$subject = ‘Birthday Reminders for August’ ;

// Message
$message = ‘

Birthday Reminders for August

Источник

mail — Отправляет электронную почту

(PHP 4, PHP 5, PHP 7)

mail — Отправляет электронную почту

Описание

Отправляет электронную почту.

Список параметров

Получатель, или получатели письма.

Формат этого параметра должен соответствовать » RFC 2822. Несколько примеров:

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User
  • User , Another User

Тема отправляемого письма.

Тема должна соответствовать » RFC 2047.

Каждая строка должна быть отделена символом CRLF (rn). Строки не должны быть длиннее 70 символов.

(Только для Windows) Если PHP передаёт данные напрямую SMTP-серверу и в начале строки стоит точка, то она будет удалена. Чтобы избежать этого замените все такие точки на две.

Строка, которая будет дополнительно вставлена в конец отправляемых заголовков письма.

Обычно используется для добавления дополнительных заголовков (From, Cc, and Bcc). Несколько дополнительных заголовков должны быть разделены CRLF (rn). Если для составления этого заголовка используются внешние данные, то они должны быть проверены для избежания инъекций нежелательных заголовков.

При отправке письмо должно содержать заголовок From. Он может быть установлен с помощью параметра additional_headers , или значение по умолчанию может быть установлено в php.ini .

Если заголовок отсутствует, будет сгенерировано сообщение об ошибке вида Warning: mail(): «sendmail_from» not set in php.ini or custom «From:» header missing. Заголовок From также определяет заголовок Return-Path в Windows.

Если сообщения не отправляются, попробуйте использовать только LF (n). Некоторые агенты пересылки сообщений Unix (особенно » qmail) автоматически заменяют LF на CRLF (что приводит к двойному CR, если использовалось CRLF). Используйте эту меру в крайнем случае, так как это нарушает » RFC 2822.

Параметр additional_parameters может быть использован для передачи дополнительных флагов в виде аргументов командной строки для программы сконфигурированной для отправки писем, указанной директивой sendmail_path. Например, можно установить отправителя письма при использовании sendmail с помощью опции -f.

Параметр автоматически экранируется функцией escapeshellcmd() , чтобы не допустить выполнение команд. Но escapeshellcmd() позволяет добавлять дополнительные параметры. В целях безопасности рекомендуется проверять и очищать этот параметр.

Так как escapeshellcmd() применяется автоматически, то нельзя использовать некоторые символы, допустимые к использованию в email-адресах некоторыми RFC. mail() не допускает такие символы, поэтому в программах, в которых они требуются, рекомендуется использовать альтернативы для их отправки (например фреймворки или библиотеки).

Пользователь, под которым работает веб-сервер должен быть добавлен в список доверенных в конфигурации sendmail для того чтобы избежать добавления заголовка ‘X-Warning’ при указании отправителя с помощью опции (-f). Для пользователей sendmail — это файл /etc/mail/trusted-users .

Возвращаемые значения

Возвращает TRUE , если письмо было принято для передачи, иначе FALSE .

Важно заметить, что то что письмо было принято для передачи вовсе НЕ означает что оно достигло получателя.

Список изменений

Версия Описание
4.2.3 Параметр additional_parameters отключен в режиме safe_mode и при его использовании функция mail() вызовет предупреждение и вернет FALSE .

Примеры

Пример #1 Отправка письма.

Использование функции mail() для отправки простого письма:

// Сообщение
$message = «Line 1rnLine 2rnLine 3» ;

// На случай если какая-то строка письма длиннее 70 символов мы используем wordwrap()
$message = wordwrap ( $message , 70 , «rn» );

// Отправляем
mail ( ‘caffeinated@example.com’ , ‘My Subject’ , $message );
?>

Пример #2 Отправка письма с дополнительными заголовками.

Добавление простых заголовков, сообщающих почтовому агенту адреса From и Reply-To:

= ‘nobody@example.com’ ;
$subject = ‘the subject’ ;
$message = ‘hello’ ;
$headers = ‘From: webmaster@example.com’ . «rn» .
‘Reply-To: webmaster@example.com’ . «rn» .
‘X-Mailer: PHP/’ . phpversion ();

mail ( $to , $subject , $message , $headers );
?>

Пример #3 Отправка письма с дополнительными аргументами командной строки.

Параметр additional_parameters может быть использован для передачи дополнительных параметров программе, используемой для отправки писем с помощью директивы sendmail_path.

Пример #4 Отправка HTML-сообщения

С помощью функции mail() также можно отправить и HTML-письмо.

// несколько получателей
$to = ‘aidan@example.com’ . ‘, ‘ ; // обратите внимание на запятую
$to .= ‘wez@example.com’ ;

// тема письма
$subject = ‘Birthday Reminders for August’ ;

// текст письма
$message = ‘

Birthday Reminders for August

Источник

Предопределённые константы

Перечисленные ниже константы всегда доступны как часть ядра PHP.

Замечание: Данные имена констант можно использовать в файле php.ini но не вне PHP, как например в файле httpd.conf , где вместо них необходимо использовать значения их битовых масок.

Ошибки и протоколирование

Значение Константа Описание Примечание
1 E_ERROR ( int ) Фатальные ошибки времени выполнения. Это неустранимые средствами самого скрипта ошибки, такие как ошибка распределения памяти и т.п. Выполнение скрипта в таком случае прекращается.
2 E_WARNING ( int ) Предупреждения времени выполнения (не фатальные ошибки). Выполнение скрипта в таком случае не прекращается.
4 E_PARSE ( int ) Ошибки на этапе компиляции. Должны генерироваться только парсером.
8 E_NOTICE ( int ) Уведомления времени выполнения. Указывают на то, что во время выполнения скрипта произошло что-то, что может указывать на ошибку, хотя это может происходить и при обычном выполнении программы.
16 E_CORE_ERROR ( int ) Фатальные ошибки, которые происходят во время запуска РНР. Такие ошибки схожи с E_ERROR , за исключением того, что они генерируются ядром PHP.
32 E_CORE_WARNING ( int ) Предупреждения (не фатальные ошибки), которые происходят во время начального запуска РНР. Такие предупреждения схожи с E_WARNING , за исключением того, что они генерируются ядром PHP.
64 E_COMPILE_ERROR ( int ) Фатальные ошибки на этапе компиляции. Такие ошибки схожи с E_ERROR , за исключением того, что они генерируются скриптовым движком Zend.
128 E_COMPILE_WARNING ( int ) Предупреждения на этапе компиляции (не фатальные ошибки). Такие предупреждения схожи с E_WARNING , за исключением того, что они генерируются скриптовым движком Zend.
256 E_USER_ERROR ( int ) Сообщения об ошибках, сгенерированные пользователем. Такие ошибки схожи с E_ERROR , за исключением того, что они генерируются в коде скрипта средствами функции PHP trigger_error() .
512 E_USER_WARNING ( int ) Предупреждения, сгенерированные пользователем. Такие предупреждения схожи с E_WARNING , за исключением того, что они генерируются в коде скрипта средствами функции PHP trigger_error() .
1024 E_USER_NOTICE ( int ) Уведомления, сгенерированные пользователем. Такие уведомления схожи с E_NOTICE , за исключением того, что они генерируются в коде скрипта, средствами функции PHP trigger_error() .
2048 E_STRICT ( int ) Включаются для того, чтобы PHP предлагал изменения в коде, которые обеспечат лучшее взаимодействие и совместимость кода.
4096 E_RECOVERABLE_ERROR ( int ) Фатальные ошибки с возможностью обработки. Такие ошибки указывают, что, вероятно, возникла опасная ситуация, но при этом, скриптовый движок остаётся в стабильном состоянии. Если такая ошибка не обрабатывается функцией, определённой пользователем для обработки ошибок (смотрите set_error_handler() ), выполнение приложения прерывается, как происходит при ошибках E_ERROR .
8192 E_DEPRECATED ( int ) Уведомления времени выполнения об использовании устаревших конструкций. Включаются для того, чтобы получать предупреждения о коде, который не будет работать в следующих версиях PHP.
16384 E_USER_DEPRECATED ( int ) Уведомления времени выполнения об использовании устаревших конструкций, сгенерированные пользователем. Такие уведомления схожи с E_DEPRECATED за исключением того, что они генерируются в коде скрипта, с помощью функции PHP trigger_error() .
32767 E_ALL ( int ) Все поддерживаемые ошибки, предупреждения и замечания.

Представленные выше значения (как числовые, так и символьные) используются для задания битовой маски, определяющей об ошибках какого типа будет даваться отчёт. Вы можете использовать побитовые операторы, чтобы совмещать эти значения для указания определённых типов ошибок. Стоит отметить, что в php.ini допустимы только следующие операторы: ‘|’, ‘

User Contributed Notes 20 notes

[Editor’s note: fixed E_COMPILE_* cases that incorrectly returned E_CORE_* strings. Thanks josiebgoode.]

The following code expands on Vlad’s code to show all the flags that are set. if not set, a blank line shows.

= error_reporting ();
for ( $i = 0 ; $i 15 ; $i ++ ) <
print FriendlyErrorType ( $errLvl & pow ( 2 , $i )) . «
\n» ;
>

function FriendlyErrorType ( $type )
<
switch( $type )
<
case E_ERROR : // 1 //
return ‘E_ERROR’ ;
case E_WARNING : // 2 //
return ‘E_WARNING’ ;
case E_PARSE : // 4 //
return ‘E_PARSE’ ;
case E_NOTICE : // 8 //
return ‘E_NOTICE’ ;
case E_CORE_ERROR : // 16 //
return ‘E_CORE_ERROR’ ;
case E_CORE_WARNING : // 32 //
return ‘E_CORE_WARNING’ ;
case E_COMPILE_ERROR : // 64 //
return ‘E_COMPILE_ERROR’ ;
case E_COMPILE_WARNING : // 128 //
return ‘E_COMPILE_WARNING’ ;
case E_USER_ERROR : // 256 //
return ‘E_USER_ERROR’ ;
case E_USER_WARNING : // 512 //
return ‘E_USER_WARNING’ ;
case E_USER_NOTICE : // 1024 //
return ‘E_USER_NOTICE’ ;
case E_STRICT : // 2048 //
return ‘E_STRICT’ ;
case E_RECOVERABLE_ERROR : // 4096 //
return ‘E_RECOVERABLE_ERROR’ ;
case E_DEPRECATED : // 8192 //
return ‘E_DEPRECATED’ ;
case E_USER_DEPRECATED : // 16384 //
return ‘E_USER_DEPRECATED’ ;
>
return «» ;
>
?>

-1 is also semantically meaningless as a bit field, and only works in 2s-complement numeric representations. On a 1s-complement system -1 would not set E_ERROR. On a sign-magnitude system -1 would set nothing at all! (see e.g. http://en.wikipedia.org/wiki/Ones%27_complement)

If you want to set all bits,

0 is the correct way to do it.

But setting undefined bits could result in undefined behaviour and that means *absolutely anything* could happen 🙂

A simple and neat way to get the error level from the error code. You can even customize the error level names further.

= [
E_ERROR => «E_ERROR» ,
E_WARNING => «E_WARNING» ,
E_PARSE => «E_PARSE» ,
E_NOTICE => «E_NOTICE» ,
E_CORE_ERROR => «E_CORE_ERROR» ,
E_CORE_WARNING => «E_CORE_WARNING» ,
E_COMPILE_ERROR => «E_COMPILE_ERROR» ,
E_COMPILE_WARNING => «E_COMPILE_WARNING» ,
E_USER_ERROR => «E_USER_ERROR» ,
E_USER_WARNING => «E_USER_WARNING» ,
E_USER_NOTICE => «E_USER_NOTICE» ,
E_STRICT => «E_STRICT» ,
E_RECOVERABLE_ERROR => «E_RECOVERABLE_ERROR» ,
E_DEPRECATED => «E_DEPRECATED» ,
E_USER_DEPRECATED => «E_USER_DEPRECATED» ,
E_ALL => «E_ALL»
];

echo $exceptions [ «1» ];
$code = 256 ;
echo $exceptions [ $code ];
?>

Output:
E_ERROR
E_USER_ERROR

This will need updating when PHP updates the error level names. Otherwise, it works just fine.

An other way to get all PHP errors that are set to be reported. This code will even work, when additional error types are added in future.

= 0 ;
foreach ( array_reverse ( str_split ( decbin ( error_reporting ()))) as $bit ) <
if ( $bit == 1 ) <
echo array_search ( pow ( 2 , $pot ), get_defined_constants ( true )[ ‘Core’ ]). «
n» ;
>
$pot ++;
>
?>

A neat way to have a place in code to control error reporting configuration 🙂

= [
E_ERROR => FALSE ,
E_WARNING => TRUE ,
E_PARSE => TRUE ,
E_NOTICE => TRUE ,
E_CORE_ERROR => FALSE ,
E_CORE_WARNING => FALSE ,
E_COMPILE_ERROR => FALSE ,
E_COMPILE_WARNING => FALSE ,
E_USER_ERROR => TRUE ,
E_USER_WARNING => TRUE ,
E_USER_NOTICE => TRUE ,
E_STRICT => FALSE ,
E_RECOVERABLE_ERROR => TRUE ,
E_DEPRECATED => FALSE ,
E_USER_DEPRECATED => TRUE ,
E_ALL => FALSE ,
];

error_reporting (
array_sum (
array_keys ( $errorsActive , $search = true )
)
);

super simple error code to human readable conversion:

function prettycode($code) <
return $code == 0 ? «FATAL» : array_search($code, get_defined_constants(true)[‘Core’]);
>

Notes posted above limited to current errors level as on 26th Aug 2016, following snippet will work even on introduction of new error level

$errLvl = error_reporting();
for ( $i = 1; $i

As for me, the best way to get error name by int value is that. And it’s works fine for me 😉
( array_slice ( get_defined_constants ( true )[ ‘Core’ ], 1 , 15 , true ))[ $type ];

//the same in readable form
array_flip (
array_slice (
get_defined_constants ( true )[ ‘Core’ ],
1 ,
15 ,
true
)
)[ $type ]

A shorter version of vladvarna’s FriendlyErrorType($type)
function getErrorTypeByValue ( $type ) <
$constants = get_defined_constants ( true );

foreach ( $constants [ ‘Core’ ] as $key => $value ) < // Each Core constant
if ( preg_match ( ‘/^E_/’ , $key ) ) < // Check error constants
if ( $type == $value )
return( » $key = $value » );
>
>
> // getErrorTypeByValue()

echo «[» . getErrorTypeByValue ( 1 ) . «]» . PHP_EOL ;
echo «[» . getErrorTypeByValue ( 0 ) . «]» . PHP_EOL ;
echo «[» . getErrorTypeByValue ( 8 ) . «]» . PHP_EOL ;
?>

Will give
[E_ERROR=1]
[]
[E_NOTICE=8]

My version!
For long list function returns for example «E_ALL without E_DEPRECATED «

function errorLevel()
<
$levels = array(
‘E_ERROR’,
‘E_WARNING’,
‘E_PARSE’,
‘E_NOTICE’,
‘E_CORE_ERROR’,
‘E_CORE_WARNING’,
‘E_COMPILE_ERROR’,
‘E_COMPILE_WARNING’,
‘E_USER_ERROR’,
‘E_USER_WARNING’,
‘E_USER_NOTICE’,
‘E_STRICT’,
‘E_RECOVERABLE_ERROR’,
‘E_DEPRECATED’,
‘E_USER_DEPRECATED’,
‘E_ALL’
);
$excluded = $included = array();
$errLvl = error_reporting();
foreach ($levels as $lvl) <
$val = constant($lvl);
if ($errLvl & $val) <
$included []= $lvl;
> else <
$excluded []= $lvl;
>
>
if (count($excluded) > count($included)) <
echo ‘
Consist: ‘.implode(‘,’, $included);
> else <
echo ‘
Consist: E_ALL without ‘.implode(‘,’, $excluded);
>
>

Well, technically -1 will show all errors which includes any new ones included by PHP. My guess is that E_ALL will always include new error constants so I usually prefer:

( E_ALL | E_STRICT );
?>

Reason being: With a quick glance anyone can tell you what errors are reported. -1 might be a bit more cryptic to newer programmers.

this would give you all the reported exception list of your configuration.

Источник

(PHP 4, PHP 5, PHP 7, PHP 8)

mailОтправляет электронную почту

Описание

mail(
    string $to,
    string $subject,
    string $message,
    array|string $additional_headers = [],
    string $additional_params = «»
): bool

Список параметров

to

Получатель, или получатели письма.

Формат этого параметра должен соответствовать
» RFC 2822. Несколько примеров:

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User <user@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>
subject

Тема отправляемого письма.

Предостережение

Тема должна соответствовать » RFC 2047.

message

Отправляемое сообщение.

Каждая строка должна быть отделена символом CRLF (rn).
Строки не должны быть длиннее 70 символов.

Предостережение

(Только для Windows) Если PHP передаёт данные напрямую SMTP-серверу и
в начале строки стоит точка, то она будет удалена. Чтобы избежать этого замените
все такие точки на две.


<?php
$text
= str_replace("n.", "n..", $text);
?>

additional_headers (необязательный)

Строка или массив, которые будут вставлены в конец отправляемых заголовков письма.

Обычно используется для добавления дополнительных заголовков (From, Cc, and Bcc).
Несколько дополнительных заголовков должны быть разделены CRLF (rn).
Если для составления этого заголовка используются внешние данные,
то они должны быть проверены для избежания инъекций нежелательных заголовков.

Если передан массив, то его ключи будут именами заголовка, а значения значениями.

Замечание:

До PHP 5.4.42 и 5.5.27, параметр additional_headers
не имел защиты от инъекции.
Так что пользователи должны удостовериться, что передаваемые заголовки
безопасны и содержат только заголовки. т.е. не содержат несколько
переводов строк подряд, что стартует тело сообщения.

Замечание:

При отправке письмо должно содержать
заголовок From. Он может быть установлен с помощью
параметра additional_headers, или значение
по умолчанию может быть установлено в php.ini.

Если заголовок отсутствует, будет сгенерировано сообщение об ошибке
вида Warning: mail(): "sendmail_from" not
set in php.ini or custom "From:" header missing
.
Заголовок From также определяет заголовок
Return-Path при отправке напрямую через SMTP (только Windows).

Замечание:

Если сообщения не отправляются, попробуйте использовать только LF (n).
Некоторые агенты пересылки сообщений Unix (особенно
» qmail) автоматически заменяют LF на CRLF
(что приводит к двойному CR, если использовалось CRLF).
Используйте эту меру в крайнем случае, так как это нарушает
» RFC 2822.

additional_params (необязательный)

Параметр additional_params может быть
использован для передачи дополнительных флагов в виде аргументов
командной строки для программы сконфигурированной для отправки писем,
указанной директивой sendmail_path. Например, можно
установить отправителя письма при использовании sendmail с помощью опции
-f.

Параметр автоматически экранируется функцией escapeshellcmd(),
чтобы не допустить выполнение команд. Но escapeshellcmd()
позволяет добавлять дополнительные параметры. В целях безопасности
рекомендуется проверять и очищать этот параметр.

Так как escapeshellcmd() применяется автоматически, то нельзя использовать
некоторые символы, допустимые к использованию в email-адресах некоторыми RFC.
mail() не допускает такие символы, поэтому в программах, в которых они требуются,
рекомендуется использовать альтернативы для их отправки (например фреймворки или библиотеки).

Пользователь, под которым работает веб-сервер должен быть добавлен в список
доверенных в конфигурации sendmail для того чтобы избежать добавления заголовка
‘X-Warning’ при указании отправителя с помощью опции (-f).
Для пользователей sendmail — это файл /etc/mail/trusted-users.

Возвращаемые значения

Возвращает true, если письмо было принято для передачи, иначе false.

Важно заметить, что то что письмо было принято для передачи вовсе НЕ означает
что оно достигло получателя.

Список изменений

Версия Описание
7.2.0 Параметр additional_headers может принимать
значения типа массив.

Примеры

Пример #1 Отправка письма.

Использование функции mail() для отправки простого письма:


<?php
// Сообщение
$message = "Line 1rnLine 2rnLine 3";// На случай если какая-то строка письма длиннее 70 символов мы используем wordwrap()
$message = wordwrap($message, 70, "rn");// Отправляем
mail('caffeinated@example.com', 'My Subject', $message);
?>

Пример #2 Отправка письма с дополнительными заголовками.

Добавление простых заголовков, сообщающих почтовому агенту
адреса From и Reply-To:


<?php
$to
= 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "rn" .
'Reply-To: webmaster@example.com' . "rn" .
'X-Mailer: PHP/' . phpversion();mail($to, $subject, $message, $headers);
?>

Пример #3 Отправка письма с дополнительными заголовками, переданными массивом

В этом примере посылается то же письмо, что и в примере выше, но
дополнительные заголовки задаются массивом (доступно с PHP 7.2.0).


<?php
$to
= 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = array(
'From' => 'webmaster@example.com',
'Reply-To' => 'webmaster@example.com',
'X-Mailer' => 'PHP/' . phpversion()
);
mail($to, $subject, $message, $headers);
?>

Пример #4 Отправка письма с дополнительными аргументами командной строки.

Параметр additional_params может быть использован
для передачи дополнительных параметров программе, используемой для отправки
писем с помощью директивы sendmail_path.


<?php
mail
('nobody@example.com', 'the subject', 'the message', null,
'-fwebmaster@example.com');
?>

Пример #5 Отправка HTML-сообщения

С помощью функции mail() также можно отправить и HTML-письмо.


<?php
// несколько получателей
$to = 'johny@example.com, sally@example.com'; // обратите внимание на запятую

// тема письма

$subject = 'Birthday Reminders for August';// текст письма
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Johny</td><td>10th</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
'
;// Для отправки HTML-письма должен быть установлен заголовок Content-type
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";// Дополнительные заголовки
$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';// Отправляем
mail($to, $subject, $message, implode("rn", $headers));
?>

Замечание:

Для отправки HTML или других комплексных сообщений рекомендуется использовать
PEAR-пакет » PEAR::Mail_Mime.

Примечания

Замечание:

Реализация SMTP (только Windows) функции mail() в Windows во многом отличается от
реализации в sendmail. Во-первых, она не использует локальную программу для
составления писем, а работает непосредственно с сокетами, что означает что
необходим почтовый агент (MTA), ожидающий
соединений на сокете (может быть как на локальном так и на
удалённом сервере).

Во-вторых, дополнительные заголовки вроде:
From:,
Cc:,
Bcc: и
Date:
интерпретируются в первую очередь не,
MTA, а PHP.

Поэтому параметр to не должен быть адресом вида
«Something <someone@example.com>». Команда
mail может неправильно интерпретировать этот адрес во время передачи
данных MTA.

Замечание:

Не следует использовать функцию mail() для отправки
большого количества писем в цикле. Функция открывает и закрывает
соединение с SMTP-сервером для каждого письма, что не очень эффективно.

Для отправки большого количества сообщений обратите внимание на пакеты
» PEAR::Mail и
» PEAR::Mail_Queue.

Замечание:

Полезные RFC:
» RFC 1896,
» RFC 2045,
» RFC 2046,
» RFC 2047,
» RFC 2048,
» RFC 2049 и
» RFC 2822.

Anonymous

3 years ago


If you notice wrong displayed characters in the email it's because you need to properly set the Content-Type and the Charset in the headers of the email:

<?php
$headers
= 'Content-Type: text/plain; charset=utf-8' . "rn";
?>

Mostly, UTF-8 is your best choice.

You can set custom headers with the fourth parameter of the mail() function.

To make the whole thing waterproof, add the following header too:

<?php
$headers
.= 'Content-Transfer-Encoding: base64' . "rn";
?>

Now you can use the combination of UTF-8 and Base64 to properly encode the subject line and the recipient name like this:

<?php
$subject
= '=?UTF-8?B?' . base64_encode('Test email with German Umlauts öäüß') . '?=';
$recipient = '=?UTF-8?B?' . base64_encode('Margret Müller') . '?= <recipient@domain.com>';
?>

And don't forget to Base64 encode the email message too:

<?php
$message
= base64_encode('This email contains German Umlauts öäüß.');
?>

All references are taken from:
https://dev.to/lutvit/how-to-make-the-php-mail-function-awesome-3cii


Anonymous

6 years ago


Security advice: Although it is not documented, for the parameters $to and $subject the mail() function changes at least r and n to space. So these parameters are safe against injection of additional headers. But you might want to check $to for commas as these separate multiple addresses and you might not want to send to more than one recipient.

The crucial part is the $additional_headers parameter. This parameter can't be cleaned by the mail() function. So it is up to you to prevent unwanted r or n to be inserted into the values you put in there. Otherwise you just created a potential spam distributor.


php at simoneast dot net

5 years ago


Often it's helpful to find the exact error message that is triggered by the mail() function. While the function doesn't provide an error directly, you can use error_get_last() when mail() returns false.

<?php
$success
= mail('example@example.com', 'My Subject', $message);
if (!
$success) {
   
$errorMessage = error_get_last()['message'];
}
?>

(Tested successfully on Windows which uses SMTP by default, but sendmail on Linux/OSX may not provide the same level of detail.)

Thanks to https://stackoverflow.com/a/20203870/195835


charles dot fisher at arconic dot com

5 years ago


I migrated an application to a platform without a local transport agent (MTA). I did not want to configure an MTA, so I wrote this xxmail function to replace mail() with calls to a remote SMTP server. Hopefully it is of some use.

function xxmail($to, $subject, $body, $headers)
{
$smtp = stream_socket_client('tcp://smtp.yourmail.com:25', $eno, $estr, 30);

$B = 8192;
$c = "rn";
$s = 'myapp@someserver.com';

fwrite($smtp, 'helo ' . $_ENV['HOSTNAME'] . $c);
  $junk = fgets($smtp, $B);

// Envelope
fwrite($smtp, 'mail from: ' . $s . $c);
  $junk = fgets($smtp, $B);
fwrite($smtp, 'rcpt to: ' . $to . $c);
  $junk = fgets($smtp, $B);
fwrite($smtp, 'data' . $c);
  $junk = fgets($smtp, $B);

// Header
fwrite($smtp, 'To: ' . $to . $c);
if(strlen($subject)) fwrite($smtp, 'Subject: ' . $subject . $c);
if(strlen($headers)) fwrite($smtp, $headers); // Must be rn (delimited)
fwrite($smtp, $headers . $c);

// Body
if(strlen($body)) fwrite($smtp, $body . $c);
fwrite($smtp, $c . '.' . $c);
  $junk = fgets($smtp, $B);

// Close
fwrite($smtp, 'quit' . $c);
  $junk = fgets($smtp, $B);
fclose($smtp);
}


pangz dot lab at gmail dot com

2 years ago


* Sending email with attachment

function sendMail(
    string $fileAttachment,
    string $mailMessage = MAIL_CONF["mailMessage"],
    string $subject     = MAIL_CONF["subject"],
    string $toAddress   = MAIL_CONF["toAddress"],
    string $fromMail    = MAIL_CONF["fromMail"]
): bool {

        $fileAttachment = trim($fileAttachment);
    $from           = $fromMail;
    $pathInfo       = pathinfo($fileAttachment);
    $attchmentName  = "attachment_".date("YmdHms").(
    (isset($pathInfo['extension']))? ".".$pathInfo['extension'] : ""
    );

        $attachment    = chunk_split(base64_encode(file_get_contents($fileAttachment)));
    $boundary      = "PHP-mixed-".md5(time());
    $boundWithPre  = "n--".$boundary;

        $headers   = "From: $from";
    $headers  .= "nReply-To: $from";
    $headers  .= "nContent-Type: multipart/mixed; boundary="".$boundary.""";

        $message   = $boundWithPre;
    $message  .= "n Content-Type: text/plain; charset=UTF-8n";
    $message  .= "n $mailMessage";

        $message .= $boundWithPre;
    $message .= "nContent-Type: application/octet-stream; name="".$attchmentName.""";
    $message .= "nContent-Transfer-Encoding: base64n";
    $message .= "nContent-Disposition: attachmentn";
    $message .= $attachment;
    $message .= $boundWithPre."--";

        return mail($toAddress, $subject, $message, $headers);
}

* Sending email in html

function sendHtmlMail(
    string $mailMessage = MAIL_CONF["mailMessage"],
    string $subject     = MAIL_CONF["subject"],
    array $toAddress    = MAIL_CONF["toAddress"],
    string $fromMail    = MAIL_CONF["fromMail"]
): bool {

        $to        = implode(",", $toAddress);
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-type: text/html; charset=iso-8859-1';   
    $headers[] = 'To: '.$to;
    $headers[] = 'From: '.$fromMail;   

    return mail($to, $subject, $mailMessage, implode("rn", $headers));
}


chris at ocproducts dot com

5 years ago


The 'sendmail' executable which PHP uses on Linux/Mac (not Windows) expects "n" as a line separator.

This executable is a standard, and emulated by other MTAs.

"n" is confirmed required for qmail and postfix, probably also for sendmail and exim but I have not tested.

If you pass through using "rn" as a separator it may appear to work, but your email will be subtly corrupted and some middleware may break. It only works because some systems will clean up your mistake.

If you are implementing DKIM be very careful, as DKIM checks will fail (at least on popular validation tools) if you screw this up. DKIM must be calculated using "rn" but then you must switch it all to "n" when using the PHP mail function.

On Windows, however, you should use "rn" because PHP is using SMTP in this situation, and hence the normal rules of the SMTP protocol (not the normal rules of Unix piping) apply.


ABOMB

11 years ago


I was having delivery issues from this function to Gmail, Yahoo, AOL, etc.  I used the notes here to figure that you need to be setting your Return-Path to a valid email to catch bounces.  There are two extra delivery gotchas on top of that:

1) The domain in the email used in the -f option in the php.ini sendmail parameter or in the mail() extra parameters field, needs to have a valid SPF record for the domain (in DNS as a "TXT" record type for sure and add an additional  "SPF" type record if possible).  Why? That's header field being used for spam checks.

2) You should also use a domain key or DKIM.  The trick here is that the domain key/DKIM is case sensitive!  I used Cpanel to create my domain key which automatically used all lowercase domain names in the key creation.  I found when  sending email and using a camel case "-f account@MyDomainHere.Com" option, my key was not accepted.  However it was accepted when I used "-f account@mydomainhere.com".

There are many other factors that can contribute to mail not getting to inboxes, including your own multiple failed testing attempts, so I suggest you consult each site's guidelines and don't ask me for help.  These are just the couple technical issues that helped my case.

I hope this saves someone some time and headaches...


Mark Simon

3 years ago


It is worth noting that you can set up a fake sendmail program using the sendmail_path directive in php.ini.

Despite the comment in that file, sendmail_path also works for Window. From https://www.php.net/manual/en/mail.configuration.php#ini.sendmail-path:

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.


Porjo

12 years ago


Make sure you enclose rn in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed code

Ben Cooke

17 years ago


Note that there is a big difference between the behavior of this function on Windows systems vs. UNIX systems. On Windows it delivers directly to an SMTP server, while on a UNIX system it uses a local command to hand off to the system's own MTA.

The upshot of all this is that on a Windows system your  message and headers must use the standard line endings rn as prescribed by the email specs. On a UNIX system the MTA's "sendmail" interface assumes that recieved data will use UNIX line endings and will turn any n to rn, so you must supply only n to mail() on a UNIX system to avoid the MTA hypercorrecting to rrn.

If you use plain old n on a Windows system, some MTAs will get a little upset. qmail in particular will refuse outright to accept any message that has a lonely n without an accompanying r.


eeeugeneee

5 years ago


Send mail with minimal requirements from email services.

<?php
    $encoding
= "utf-8";// Preferences for Subject field
   
$subject_preferences = array(
       
"input-charset" => $encoding,
       
"output-charset" => $encoding,
       
"line-length" => 76,
       
"line-break-chars" => "rn"
   
);// Mail header
   
$header = "Content-type: text/html; charset=".$encoding." rn";
   
$header .= "From: ".$from_name." <".$from_mail."> rn";
   
$header .= "MIME-Version: 1.0 rn";
   
$header .= "Content-Transfer-Encoding: 8bit rn";
   
$header .= "Date: ".date("r (T)")." rn";
   
$header .= iconv_mime_encode("Subject", $mail_subject, $subject_preferences);// Send mail
   
mail($mail_to, $mail_subject, $mail_message, $header);
?>


atesin > gmail

18 days ago


mail() internals:

doing some tests i can say... if sendmail_path is defined in php.ini or by ini.set(), by calling function like...

mail($to, $subject, $message, $headers, $params)

would be like if php open a shell internally, execute this command, send this text to stdin, and return true if return value == 0

------------
shell> $sendmail_path $params
To: $to
Subject: $subject
$headers

$message
(EOF)
------------

in windows instead using php smtp which is very limited, i prefer to force use sendmail-like behavior, by setting sendmail_path and then use msmtp for windows


rexlorenzo at gmail dot com

10 years ago


Be careful to not put extra spaces for the $headers variable.

For example, this didn't work on our servers:

$headers = "From: $from rn Bcc: $bcc rn";

But this did:

$headers = "From: $fromrnBcc: $bccrn";

Notice the removal of the spaces around the first rn.


pavel.lint at vk.com

10 years ago


Here's a small handy function I use to send email in UTF-8.

<?php
function mail_utf8($to, $from_user, $from_email,
                                            
$subject = '(No subject)', $message = '')
   {
     
$from_user = "=?UTF-8?B?".base64_encode($from_user)."?=";
     
$subject = "=?UTF-8?B?".base64_encode($subject)."?=";$headers = "From: $from_user <$from_email>rn".
              
"MIME-Version: 1.0" . "rn" .
              
"Content-type: text/html; charset=UTF-8" . "rn";

     return

mail($to, $subject, $message, $headers);
   }
?>


Max AT

10 years ago


To define a mail sensitivity you have to put this line in the headers:

<?php
        $headers
= "MIME-Version: 1.0n" ;
       
$headers .= "Content-Type: text/html; charset="iso-8859-1"n";$headers .= "Sensitivity: Personaln";$status   = mail($to, $subject, $message,$headers);
?>

Possible Options:
Sensitivity: Normal, Personal, Private and Company-Confidential

These will be recognised and handled in Outlook, Thunderbird and others.


andrew at my-syte dot com

3 months ago


Regarding To:

be careful not to duplicate To in the additional_headers,

lest gmail already flags it thus:

host gmail-smtp-in.l.google.com [142.251.xx.xx]
SMTP error from remote mail server after end of data:
550-5.7.1 [xxx.xxx.xx.xx] This message is not RFC 5322 compliant, the issue is:
550-5.7.1 duplicate To headers. To reduce the amount of spam sent to Gmail,
550-5.7.1 this message has been blocked. Please review
550 5.7.1 RFC 5322 specifications for more information.


php dot net at schrecktech dot com

17 years ago


When sending MIME email make sure you follow the documentation with the "70" characters per line...you may end up with missing characters...and that is really hard to track down...

Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php and checkErrorEmail.php and uploaded them to your server. Then load index.php with your browser.

Index.php

<?php
    include('checkErrorEmail.php');
    include('dereporting.php');
    $temp;
    echo 'hi '.$temp;
?>

checkErrorEmail.php

<?php
  // Destinations
  define("ADMIN_EMAIL", "pradeep.callus7@hotmail.com");
  //define("LOG_FILE", "/my/home/errors.log");

  // Destination types
  define("DEST_EMAIL", "1");
  //define("DEST_LOGFILE", "3");

  /* Examples */

  // Send an e-mail to the administrator
  //error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);

  // Write the error to our log file
  //error_log("Error", DEST_LOGFILE, LOG_FILE);

  /**
    * my_error_handler($errno, $errstr, $errfile, $errline)
    *
    * Author(s): thanosb, ddonahue
    * Date: May 11, 2008
    * 
    * custom error handler
    *
    * Parameters:
    *  $errno:   Error level
    *  $errstr:  Error message
    *  $errfile: File in which the error was raised
    *  $errline: Line at which the error occurred
    */

  function my_error_handler($errno, $errstr, $errfile, $errline)
  {  
  echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
      if($errno)
      {
              error_log("Error: $errstr n error on line $errline in file $errfile n", DEST_EMAIL, ADMIN_EMAIL);
      }
    /*switch ($errno) {
      case E_USER_ERROR:
        // Send an e-mail to the administrator
        error_log("Error: $errstr n Fatal error on line $errline in file $errfile n", DEST_EMAIL, ADMIN_EMAIL);

        // Write the error to our log file
        //error_log("Error: $errstr n Fatal error on line $errline in file $errfile n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_WARNING:
        // Write the error to our log file
        //error_log("Warning: $errstr n in $errfile on line $errline n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_NOTICE:
        // Write the error to our log file
       // error_log("Notice: $errstr n in $errfile on line $errline n", DEST_LOGFILE, LOG_FILE);
        break;

      default:
        // Write the error to our log file
        //error_log("Unknown error [#$errno]: $errstr n in $errfile on line $errline n", DEST_LOGFILE, LOG_FILE);
        break;
    }*/

    // Don't execute PHP's internal error handler
    return TRUE;
  }


  // Use set_error_handler() to tell PHP to use our method
  $old_error_handler = set_error_handler("my_error_handler");


?>

I am new to PHP and I’m using the mail function to send emails which is not working. I get a success message, but still it does not work

same code

<?php
    $email_to = "abc@abc.com";
    $email_subject = "Test mail";
    $email_body = "Hello! This is a simple email message.";


    if(mail($email_to, $email_subject, $email_body)){
        echo "The email($email_subject) was successfully sent.";
    } else {
        echo "The email($email_subject) was NOT sent.";
    }
?>

Am I missing anything, do I need to include any files for this function.. I am from asp.net & this is the basic script which found on website.

I tried other scripts related to mail they didn’t work either..

I AM RUNNING THIS SCRIPT ON THE WEBSITE NOT on the localhost

Rich's user avatar

Rich

5,5559 gold badges37 silver badges60 bronze badges

asked Jan 10, 2012 at 13:27

Learning's user avatar

6

If you are using Ubuntu and it seem sendmail is not in /usr/sbin/sendmail, install sendmail using the terminal with this command:

sudo apt-get install sendmail

and then run reload the PHP page where mail() is written. Also check your spam folder.

Cody Gray's user avatar

Cody Gray

236k50 gold badges486 silver badges567 bronze badges

answered Jan 19, 2014 at 19:48

Prabhat Kashyap's user avatar

Prabhat KashyapPrabhat Kashyap

9761 gold badge7 silver badges11 bronze badges

1

This is probably a configuration error. If you insist on using PHP mail function, you will have to edit php.ini.

If you are looking for an easier and more versatile option (in my opinion), you should use PHPMailer.

Cody Gray's user avatar

Cody Gray

236k50 gold badges486 silver badges567 bronze badges

answered Jan 10, 2012 at 13:30

Orentet's user avatar

OrentetOrentet

2,3531 gold badge17 silver badges28 bronze badges

2

This might be the issue of your SMTP config in your php.ini file.

Since you new to PHP, You can find php.ini file in your root directory of PHP installation folder and check for SMTP = and smtp_port= and change the value to

SMTP = your mail server e.g) mail.yourdomain.com
smtp_port = 25(check your admin for original port)

In case your server require authentication for sending mail, use PEAR mail function.

answered Jan 10, 2012 at 13:40

Robin Michael Poothurai's user avatar

The mail function do not guarantee the actual delivery of mail. All it do is to pass the message to external program (usually sendmail). You need a properly configured SMTP server in order for this to work. Also keep in mind it does not support SMTP authentication. You may check out the PEAR::Mail library of SwiftMailer, both of them give you more options.

answered Jan 10, 2012 at 13:32

Maxim Krizhanovsky's user avatar

Check your SMTP settings in your php.ini file. Your host should have some documentation about what credentials to use. Perhaps you can check your error log file, it might have more information available.

answered Jan 10, 2012 at 13:31

TJHeuvel's user avatar

TJHeuvelTJHeuvel

12.2k4 gold badges37 silver badges46 bronze badges

I am new to PHP and I’m using the mail function to send emails which is not working. I get a success message, but still it does not work

same code

<?php
    $email_to = "abc@abc.com";
    $email_subject = "Test mail";
    $email_body = "Hello! This is a simple email message.";


    if(mail($email_to, $email_subject, $email_body)){
        echo "The email($email_subject) was successfully sent.";
    } else {
        echo "The email($email_subject) was NOT sent.";
    }
?>

Am I missing anything, do I need to include any files for this function.. I am from asp.net & this is the basic script which found on website.

I tried other scripts related to mail they didn’t work either..

I AM RUNNING THIS SCRIPT ON THE WEBSITE NOT on the localhost

Rich's user avatar

Rich

5,5559 gold badges37 silver badges60 bronze badges

asked Jan 10, 2012 at 13:27

Learning's user avatar

6

If you are using Ubuntu and it seem sendmail is not in /usr/sbin/sendmail, install sendmail using the terminal with this command:

sudo apt-get install sendmail

and then run reload the PHP page where mail() is written. Also check your spam folder.

Cody Gray's user avatar

Cody Gray

236k50 gold badges486 silver badges567 bronze badges

answered Jan 19, 2014 at 19:48

Prabhat Kashyap's user avatar

Prabhat KashyapPrabhat Kashyap

9761 gold badge7 silver badges11 bronze badges

1

This is probably a configuration error. If you insist on using PHP mail function, you will have to edit php.ini.

If you are looking for an easier and more versatile option (in my opinion), you should use PHPMailer.

Cody Gray's user avatar

Cody Gray

236k50 gold badges486 silver badges567 bronze badges

answered Jan 10, 2012 at 13:30

Orentet's user avatar

OrentetOrentet

2,3531 gold badge17 silver badges28 bronze badges

2

This might be the issue of your SMTP config in your php.ini file.

Since you new to PHP, You can find php.ini file in your root directory of PHP installation folder and check for SMTP = and smtp_port= and change the value to

SMTP = your mail server e.g) mail.yourdomain.com
smtp_port = 25(check your admin for original port)

In case your server require authentication for sending mail, use PEAR mail function.

answered Jan 10, 2012 at 13:40

Robin Michael Poothurai's user avatar

The mail function do not guarantee the actual delivery of mail. All it do is to pass the message to external program (usually sendmail). You need a properly configured SMTP server in order for this to work. Also keep in mind it does not support SMTP authentication. You may check out the PEAR::Mail library of SwiftMailer, both of them give you more options.

answered Jan 10, 2012 at 13:32

Maxim Krizhanovsky's user avatar

Check your SMTP settings in your php.ini file. Your host should have some documentation about what credentials to use. Perhaps you can check your error log file, it might have more information available.

answered Jan 10, 2012 at 13:31

TJHeuvel's user avatar

TJHeuvelTJHeuvel

12.2k4 gold badges37 silver badges46 bronze badges

Php mail functionsAre you having trouble understanding PHP mail functions and experiencing PHP mail not working? Have you recently swedged to understand how PHP mail works? You’ve come to the right place, as we have demystified most possible problems you could face with non working PHP mail.

Are you a PHP professional, or perhaps a novice who has yet to master the ropes? Irrespective of the circumstance, there is still more to know about any programming language, and there are occasionally materials that will help developers get better. This is one of them!

Our skilled team has gone above and beyond to explain the concept in this topic to assist you in understanding the scope and concept of how PHP mail works, error handling within a PHP mail function, setting it up to work, and sending PHP mail through Gmail. Here we begin our quest to become a better PHP developer.

Your task now is to give it your all and absorb the information you’ve been given.

The PHP mail() function allows users to send emails to users by using a script. This function takes three necessary input arguments that define the recipient’s email address, its subject, and the message to be sent as well as two optional parameters which are the headers and parameters.

Moving on with the PHP mail() function, the general syntax of this function is as follows:

Mail() can have these parameters inside its brackets: mail(to, subject, message, headers, parameters)

MorParameter values and description are in the table below

Parameter Description
Required – The following parameters are necessary
to Receiver, or receivers of the mail
subject The main topic of the mail. Note: This parameter should not have any newline characters
message The message to be sent. Note: Each line should be separated by a line feed-LF (n). Lines should not be more than 70 characters long.
Optional – The following parameters are optional
headers Headers, such as From, Cc, and Bcc, can be specified. A carriage return line feed CRLF (rn) should be used to separate the extra headers.

Note: When sending an email, it must have a From header. This may be configured using this argument or in the php.ini file.

parameters Used to input extra  or additional parameters

An example of how to you PHP mail()

<?php

$to = ‘johndoe@email.com’;

$subject = ‘Job Offer’;

$message = ‘Would you be interested in working with us?’;

$from = ‘janejoe@email.com’;

//Sending email

if(mail($to, $subject, $message)) {

echo ‘Your mail has been sent successfully.’;

} else{

echo ‘Unable to send email. Please try again.’;

}

?>

Output:

PHP Warning: mail(): Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:UsersPromise NwhatorDocumentsArticlesPHPCodetest.php on line 8

Warning: mail(): Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:UsersPromise NwhatorDocumentsArticlesPHPCodetest.php on line 8

Unable to send email. Please try again.

From the above, you can see the PHP mail function is not working.

For PHP mail to work, it requires a delivery server (SMTP) to send out emails. If you’ve ever sent emails from an application or website while it’s in production, you’re aware of the concern that an email may be exposed to the world.

Are you sure that none of the ‘test’ emails was sent to colleagues or, still, customers? Of course, you may set up and manage a test email server for development purposes, but this is a time-consuming task. Furthermore, the time it takes to examine new test emails might significantly impede your development cycle.

To use PHP mail on your localhost, you require an SMTP(Simple Mail Transfer Protocol). The Simple Mail Transfer Protocol (SMTP) is a program that allows senders and receivers to send, receive, and redirect outgoing emails. Email is transmitted from one server to another across the Internet via SMTP whenever a mail is sent. In layman’s terms, an SMTP email is just an email sent through the SMTP server. The application I currently use on an SMTP server on my localhost is called PaperCut.

The reason why PHP mail is not working are listed below:

Some email service providers do not allow external recipients through PHP mail functions when not working with the localhost. Firstly, change the recipient ($to) from the code above to a local recipient. Simply saying, the email address to be sent to would be from the server’s domain.

Follow the steps below to send mail from the localhost XAMPP using Gmail:

  1. Open your compiler (Visual Studio Code)
  2. Locate file path “C:xamppphp” and open the “php.ini” filePhp mail not working e
  3. Locate [mail function] within the filePhp mail not working e
  4. Change the values for the following,
    • SMTP = smtp.gmail.com
    • smtp_port = 587
    • sendmail_from = “Gmail username goes here”@gmail.com
    • sendmail_path = “”C:xamppsendmailsendmail.exe” -t” – Only needed in a Unix environment
  5. Then, locate file path C:xamppsendmail and open the sendmail.ini file
  6. Locate [sendmail] within the filePhp mail not working e
  7. Change the values for the following,
    • smtp_server = smtp.gmail.com
    • smtp_port = 587
    • error_logfile = error.log (Some of this code may have been commented out, just remove the; character)
    • debug_logfile = debug.log
    • auth_username = “enter Gmail username here”@gmail.com
    • auth_password= “your Gmail password goes here”

After the setup has been completed, run the code below again:

<?php
$to = ‘johndoe@email.com’;
$subject = ‘Job Offer’;
$message = ‘Would you be interested in working with us?’;
$from = ‘janejoe@email.com’;
//Sending email
if(mail($to, $subject, $message)) {
echo ‘Your mail has been sent successfully.’;
} else{
echo ‘Unable to send email. Please try again.’;
}
?>

Steps in PHP Mail Test

The script below helps test your hosting to check that you can send emails from PHP-enabled websites with a contact form or something requiring you to send emails to users. The script is used in software, including content management systems (CMS) like WordPress, Wix, Joomla, and the likes.

If you have made adjustments (such as enabling SMTP in PHP settings), this is a fast and straightforward method to ensure the emails are correctly sent.

Create a test script (name the script test.php)  with the following code below:

<?php
ini_set(‘Show errors here’), 1);
error_reporting(E_ALL);
//Write your Email Test address here
$from = “testemail@domain.com”;
//Write the email address you are sending the email to
$to = “username@domain.com”;
$subject = “PHP Mail Test”;
$message = “This is a simple test to check if your PHP Mail works”;
//Remember the header parameter is optional
$headers = “From:” . $from;
mail($to, $subject, $message, $headers);
$sent_mail = mail ($to, $subject, $message, $headers);
$error_message = “Mail not sending”;if ($sent_mail) echo ‘Mail sent successfully!’;
else echo $error_message;
?>

Login in to your server, either your shared hosting or Virtual Private Server (VPS) preferably, and execute the code below.

PHP Mail Error Handling – The Right Way

There are different ways errors can be detected while using the PHP mail function. If your mail does not send for any reason, you can try the method below to display where the error is from.

<?php
ini_set(‘Show errors here’), 1);
error_reporting(E_ALL);
//Write your Email Test address here
$from = “testemail@domain.com”;
//Write the email address you are sending the email to
$to = “username@domain.com”;
$subject = “PHP Mail Test”;
$message = “This is a simple test to check if your PHP Mail works”;
//Remember the header parameter is optional
$headers = “From:” . $from;
mail($to, $subject, $message, $headers);
$sent_mail = mail ($to, $subject, $message, $headers);
$error_message = “Mail not sending”;
if ($sent_mail) echo ‘Mail sent successfully!’;
else echo $error_message;
?>

Because the mail above has not been connected to the service, the $error_message is expected to be displayed in the output; let’s see.

Output:

Conclusion

Without hesitation, we have concentrated on all of the strategies, methods, and actions regarding everything you need to know about PHP mail. In grasping how to resolve errors while using the PHP mail function without stress.  To wrap things up, here’s a quick rundown of what we’ve covered here so far:

  • Php mail not workingPHP mail() function allows users to send emails to users by using a script
  • PHP mail requires three (3) parameters before it can work properly. First, ‘to’ (receiver of the mail), then ‘subject’ (the main topic of the mail – This parameter should not have any newline characters), lastly, ‘message’ (The content to be sent.
  • Note: Each line should be separated by a line feed-LF (n). Lines should not be more than 70 characters long).
  • Some optional parameters may not be required to be added by the user, which are the headers and other parameters.
  • PHP mail syntax is mail(to, subject, message, headers, parameters)

We have provided enough information needed to fix errors in PHP mail. PHP mail is essential when working with contact forms on your website, either developed from scratch or through a CMS such as WordPress, Joomla, Magneto, etc.

Have fun programming.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Понравилась статья? Поделить с друзьями:
  • Что означает parse error
  • Что означает on error resume next
  • Что обозначает ошибка 1042 мтс
  • Что означает nsis error
  • Что означает no atomizer на аегисе как исправить