How to send email php
How to send email php
(PHP 4, PHP 5, PHP 7)
mail — Отправляет электронную почту
Описание
Отправляет электронную почту.
Список параметров
Получатель, или получатели письма.
Тема отправляемого письма.
Тема должна соответствовать » RFC 2047.
Каждая строка должна быть отделена символом CRLF (\r\n). Строки не должны быть длиннее 70 символов.
(Только для Windows) Если PHP передаёт данные напрямую SMTP-серверу и в начале строки стоит точка, то она будет удалена. Чтобы избежать этого замените все такие точки на две.
Строка, которая будет дополнительно вставлена в конец отправляемых заголовков письма.
Обычно используется для добавления дополнительных заголовков (From, Cc, and Bcc). Несколько дополнительных заголовков должны быть разделены CRLF (\r\n). Если для составления этого заголовка используются внешние данные, то они должны быть проверены для избежания инъекций нежелательных заголовков.
Если заголовок отсутствует, будет сгенерировано сообщение об ошибке вида 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() применяется автоматически, то нельзя использовать некоторые символы, допустимые к использованию в email-адресах некоторыми RFC. mail() не допускает такие символы, поэтому в программах, в которых они требуются, рекомендуется использовать альтернативы для их отправки (например фреймворки или библиотеки).
Возвращаемые значения
Важно заметить, что то что письмо было принято для передачи вовсе НЕ означает что оно достигло получателя.
Список изменений
Примеры
Пример #1 Отправка письма.
Использование функции mail() для отправки простого письма:
// Сообщение
$message = «Line 1\r\nLine 2\r\nLine 3» ;
Пример #2 Отправка письма с дополнительными заголовками.
Добавление простых заголовков, сообщающих почтовому агенту адреса From и Reply-To:
Пример #3 Отправка письма с дополнительными аргументами командной строки.
Параметр additional_parameters может быть использован для передачи дополнительных параметров программе, используемой для отправки писем с помощью директивы sendmail_path.
Пример #4 Отправка HTML-сообщения
С помощью функции mail() также можно отправить и HTML-письмо.
// тема письма
$subject = ‘Birthday Reminders for August’ ;
// текст письма
$message = ‘
Birthday Reminders for August
How to Send Email using PHP mail() Function
Updated July 26, 2022
What is PHP mail?
PHP mail is the built in PHP function that is used to send emails from PHP scripts.
The mail function accepts the following parameters:
In this tutorial, you will learn-
Why/When to use the mail PHP
Sending mail using PHP
The PHP mail function has the following basic syntax
Simple Mail Transmission Protocol (SMTP)
PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail.
On a hosted server, the SMTP settings would have already been set.
The SMTP mail settings can be configured from “php.ini” file in the PHP installation folder.
Configuring SMTP settings on your localhost Assuming you are using xampp on windows, locate the “php.ini” in the directory “C:\xampp\php”.
PHP Mail Example
Let’s now look at an example that sends a simple mail.
Output:
Note: the above example only takes the 4 mandatory parameters.
You should replace the above fictitious email address with a real email address.
Sanitizing email user inputs
The above example uses hard coded values in the source code for the email address and other details for simplicity.
Let’s assume you have to create a contact us form for users fill in the details and then submit.
Let’s create a custom function that validates and sanitizes the email address using the filter_var built in function.
Filter_var function The filter_var function is used to sanitize and validate the user input data.
It has the following basic syntax.
The code below implements uses a custom function to send secure mail.
Output:
Secure Mail
Emails can be intercepted during transmission by unintended recipients.
This can exposure the contents of the email to unintended recipients.
Secure mail solves this problem by transmitting emails via Hypertext Transfer Protocol Secure (HTTPS).
HTTPS encrypts messages before sending them.
5 Different Ways To Send an Email with PHP
Introduction
All customer-centric applications require users to stay informed of application events such as receiving password resets, account confirmation, and payment processing. It takes time for users to see these notifications or never see them if they don’t log into the application. Therefore, many developers adopted emails to notify users as they provided a quick, readily accessible channel to create event-driven alerts to notify the users instantly. It helps users stay up-to-date on application events. When building large-scale web applications with PHP, you may require an event-driven notification system to notify your users instantly.
In this article, I will present five ways of sending an email using PHP while addressing the pros and cons of each method.
Pre-requisites to Email Sending
Templated Emails vs. Plain Text Emails
A templated email uses HTML and CSS styling to make it look appealing to users.
However, if your requirement is only plain text with a minimal body, a simple text email will do the job.
After deciding the type of email you want to send, you can use any of the five ways elaborated below to send an email from your PHP application.
1. Sending an email using the PHP Web Server
There are pros and cons to using the inbuilt mail() function. Let us look at this in detail.
Demonstration
The function shown above is the PHP mail function. As you can see, it accepts five parameters. But you can send an email using the four parameters discussed below.
Defining the sender email
To add your sender configuration, visit the php.ini file and add your mail server configs, including the sender email address.
Sending the email using mail()
After setting up the php.ini file, sending the email is as simple as shown below.
Hello! How are you doing. This is a test email to demonstrate email sending in PHP using the mail() function!
How PHP email sending works: SMTP authentication and HTML templates
The article on How to Send Emails in PHP was originally published at Mailtrap’s blog.
Today I’d love to share with you PHP email sending guide, one of the most popular web development languages.
There are two basic ways of sending emails with PHP: built-in mail function and external mail packages.
PHP’s built-in mail function () is very simple but at the same time, it provides a limited functionality for sending emails. You won’t be able to add attachments to your email, and building a beautiful HTML template with embedded images will be a tricky task as well.
The other side of the PHP mail function () is that the email is sent from your web server, which may cause issues with deliverability due to security concerns such as suspicion of spam and blacklisting. The best way to overcome this problem is sending messages via an SMTP server, however, this functionality is limited as well. PHP mail() does not usually allow you to use the external SMTP server and it does not support SMTP authentication.
In other words, I don’t recommend using the PHP built-in mail function() and advise you to avoid the headaches it may cause by installing an external mailer package.
If you are still committed to the PHP built-in mail function() and are ready to accept the challenge, let’s take a look at the basic code and its main parameters.
Syntax and parameters
The PHP mail syntax is pretty simple:
It uses the following parameters:
For more details and additional parameters, refer to the PHP documentation.
The body of the message can be written in HTML. However, as I’ve mentioned above, it should be simple. In the PHP mail function(), the HTML part will look like this:
It’s important to remember that to send HTML mail, you need to set the Content-type header:
Where do I specify the SMTP settings? This is a fair question. Go to the PHP installation folder and configure them in the “php.ini” file. But this will only work for localhost or Xmapp like solutions because as I have already mentioned, PHP mail function does not support SMTP authentication and doesn’t allow sending messages via external servers.
There are some other, rather haphazard options but I won’t promote them and recommend using external PHP mail packages for sending emails via an external SMTP server.
PHPMailer is the classic email sending library for PHP. It supports several ways of sending email messages such as mail(), Sendmail, qmail, and direct dispatch to SMTP servers. Besides, it provides a list of advanced features:
To send emails with PHPMailer and SMTP, you need to install PHPMailer and configure SMTP settings first.
Up to version 5, PHPMailer was providing “PHPMailerAutoload.php” file, so it was required just to include it in your script and create a PHPMailer instance.
Starting from PHPMailer 6.0 release in August 2017, you need to install it, preferably via Composer, a dependency manager for PHP (this way is recommended by PHPMailer’s creators on Github). After installing Composer, add this line to your composer.json file:
If you don’t want to install Composer, for example, while working within a testing environment, you can download files with PHPMailer source code, then copy the contents of the PHPMailer folder to one of the include_path directories specified in your PHP configuration, and load each class file manually:
Adding Exception class will help you handle errors and debug them. In PHP it works similarly to the other programming languages. So, without it, if there is an error in your email sending code, you will just see a message saying Exception class is not found, but you won’t be provided with any details on how to debug it. I will describe debugging is a separate section of this post.
To see detailed instructions on installation, check PHPMail documentation on Github.
To test PHP mail functionality, I will use Mailtrap, a fake SMTP server, not to flood our inboxes or even worse, the inboxes of our customers. Once you make sure that everything works properly and your email messages look right, you will easily be able to substitute the SMTP settings in our examples with your real server’s, whether you prefer a local one or a third-party service, like Gmail. (Just note that If you want to use the Gmail XOAUTH2 authentication class, you will also need to add a dependency on the league/oauth2-client package in your composer.json.)
Most likely, you will use HTML to design your email notification. So, let’s review some examples of using HTML methods and attributes.
Basic HTML message
In any case, I start with PHPMailer class:
If you have used Composer for installation, include the Composer generated autoload.php file:
Now let’s move to an SMTP configuration:
Specify the recipient of your message:
Optionally you can add a CC:
Set a subject for your message:
Then set the email format to HTML with isHTML(true) property:
Now you can input the desired content:
With PHPMailer, you can also make a nice HTML email, with custom formatting, images, and send emails with attachments. For your convenience, PHPMailer provides an option to read an HTML message body from an external file, convert referenced images to embedded as well as convert HTML into a basic plain-text alternative body. This way, you will not overload your message sending code with HTML and will be able to update your HTML template independently. To include a separate HTML file, add these attributes:
In the end, specify the email sending attributes:
The result “Message has been sent” informs you that your code executes correctly. To check the delivery result and details, go to your Mailtrap inbox: your messages will get there in seconds.
With Mailtrap, you will be able to review your HTML code, raw data, perform email browser testing as well as make sure your message won’t be marked as spam, or your sending domain won’t go blacklisted.
Once you have verified that your PHPMailer sending result matches your expectations, you can switch to regular email sending via any preferred SMTP server.
For more configuration examples, check the “examples” folder inside PHPMailer documentation.
If you experience some troubles when sending emails through an SMTP server, the SMTPDebug command will help you explore those errors and find out what should be fixed.
Enable SMTP debugging and set the debug level in your script as follows:
For a better understanding of how debugging in PHPMailer works, let’s review a couple of examples.
Example1. Invalid SMTP hostname
For this example, I entered an invalid hostname: mailtrap.io instead of smtp.mailtrap.io. and instantly received a message that an error occurred at the very first stage of communication with the server.
Example 2. Invalid credentials
This example demonstrates where the error occurs: now the SMTP, its hostname, and port are valid but a combination of login and password was not found, so you should double-check and modify your credentials.
There are a couple of detailed articles on GitHub about debugging and troubleshooting, refer to them when you need to dive deeper into these topics.
In this article, I have described the basic PHP email sending principles, syntax, and parameters. Besides, I have reviewed two main ways of sending emails with PHP: its built-in mail function and PHPMailer, the most popular external mail package.
Undoubtedly, the second one is a much more advanced solution, with SMTP authentication support and a wide set of HTML related features, however, PHP mail function() can still be an option if you are sending plain text notification via localhost.
Beyond PHPMailer, there are a bunch of other noteworthy solutions for building an HTML email and sending it via an SMTP server, such as PEAR mail package, Swift Mailer, or Zend Framework.
I will review them and other PHP mail sending options in future posts.
How to send email php
(PHP 4, PHP 5, PHP 7, PHP 8)
mail — Отправляет электронную почту
Описание
Отправляет электронную почту.
Список параметров
Получатель, или получатели письма.
Тема отправляемого письма.
Тема должна соответствовать » RFC 2047.
Каждая строка должна быть отделена символом CRLF (\r\n). Строки не должны быть длиннее 70 символов.
(Только для Windows) Если PHP передаёт данные напрямую SMTP-серверу и в начале строки стоит точка, то она будет удалена. Чтобы избежать этого замените все такие точки на две.
Строка или массив, которые будут вставлены в конец отправляемых заголовков письма.
Обычно используется для добавления дополнительных заголовков (From, Cc, and Bcc). Несколько дополнительных заголовков должны быть разделены CRLF (\r\n). Если для составления этого заголовка используются внешние данные, то они должны быть проверены для избежания инъекций нежелательных заголовков.
Если передан массив, то его ключи будут именами заголовка, а значения значениями.
До PHP 5.4.42 и 5.5.27, параметр additional_headers не имел защиты от инъекции. Так что пользователи должны удостовериться, что передаваемые заголовки безопасны и содержат только заголовки. т.е. не содержат несколько переводов строк подряд, что стартует тело сообщения.
Если сообщения не отправляются, попробуйте использовать только LF (\n). Некоторые агенты пересылки сообщений Unix (особенно » qmail) автоматически заменяют LF на CRLF (что приводит к двойному CR, если использовалось CRLF). Используйте эту меру в крайнем случае, так как это нарушает » RFC 2822.
Так как escapeshellcmd() применяется автоматически, то нельзя использовать некоторые символы, допустимые к использованию в email-адресах некоторыми RFC. mail() не допускает такие символы, поэтому в программах, в которых они требуются, рекомендуется использовать альтернативы для их отправки (например фреймворки или библиотеки).
Возвращаемые значения
Важно заметить, что то что письмо было принято для передачи вовсе НЕ означает что оно достигло получателя.
Список изменений
Версия | Описание |
---|---|
7.2.0 | Параметр additional_headers может принимать значения типа массив. |
Примеры
Пример #1 Отправка письма.
Использование функции mail() для отправки простого письма:
// Сообщение
$message = «Line 1\r\nLine 2\r\nLine 3» ;
Пример #2 Отправка письма с дополнительными заголовками.
Добавление простых заголовков, сообщающих почтовому агенту адреса From и Reply-To:
Пример #3 Отправка письма с дополнительными заголовками, переданными массивом
В этом примере посылается то же письмо, что и в примере выше, но дополнительные заголовки задаются массивом (доступно с PHP 7.2.0).
Пример #4 Отправка письма с дополнительными аргументами командной строки.
Пример #5 Отправка HTML-сообщения
С помощью функции mail() также можно отправить и HTML-письмо.
// несколько получателей
$to = ‘johny@example.com, sally@example.com’ ; // обратите внимание на запятую
// тема письма
$subject = ‘Birthday Reminders for August’ ;
// текст письма
$message = ‘
Birthday Reminders for August