What's new
HTML Forums | An HTML and CSS Coding Community

Welcome to HTMLForums; home of web development discussion! Please sign in or register your free account to get involved. Once registered you will be able to connect with other members, send and receive private messages, reply to topics and create your very own. Our registration process is hassle-free and takes no time at all!

How to Send Email using PHP mail() Function

Universe

New member

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:
  • Email address
  • Subject
  • Message
  • CC or BC email addresses
    • It’s a cost-effective way of notifying users of important events.
    • Let users contact you via email by providing a contact us form on the website that emails the provided content.
    • Developers can use it to receive system errors by email
    • You can use it to email your newsletter subscribers.
    • You can use it to send password reset links to users who forget their passwords
    • You can use it to email activation/confirmation links. This is useful when registering users and verifying their email addresses

Why/When to use the mail PHP​

Sending mail using PHP​

The PHP mail function has the following basic syntax

Code:
<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>
HERE,
  • “$to_email_address” is the email address of the mail recipient
  • “$subject” is the email subject
  • “$message” is the message to be sent.
  • “[$headers]” is optional, it can be used to include information such as CC, BCC
    • CC is the acronym for carbon copy. It’s used when you want to send a copy to an interested person i.e. a complaint email sent to a company can also be sent as CC to the complaints board.
    • BCC is the acronym for blind carbon copy. It is similar to CC. The email addresses included in the BCC section will not be shown to the other recipients.

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”.

  • Open it using notepad or any text editor. We will use notepad in this example. Click on the edit menu
How to MAIL using PHP or Phpmailer

  • Click on Find… menu
How to MAIL using PHP or Phpmailer

  • The find dialog menu will appear
How to MAIL using PHP or Phpmailer

  • Click on Find Next button
How to MAIL using PHP or Phpmailer

  • Locate the entries
    • [mail function]
    • ; XAMPP: Don’t remove the semi column if you want to work with an SMTP Server like Mercury
    • ; SMTP = localhost
    • ; smtp_port = 25
    • Remove the semi-colons before SMTP and smtp_port and set the SMTP to your SMTP server and the port to your SMTP port. Your settings should look as follows
      • SMTP = smtp.example.com
      • smtp_port = 25
      • Note the SMTP settings can be gotten from your web hosting providers.
      • If the server requires authentication, then add the following lines.
PHP Mail Example

Let’s now look at an example that sends a simple mail.

Code:
<?php   
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>
Output:

phpemail_1.png


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.
  • Users can accidentally or intentional inject code in the headers which can result in sending spam mail
  • To protect your system from such attacks, you can create a custom function that sanitizes and validates the values before the mail is sent.
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.

Code:
<?php
filter_var($field, SANITIZATION TYPE);
?>

HERE,
  • “filter_var(…)” is the validation and sanitization function
  • “$field” is the value of the field to be filtered.
  • “SANITIZATION TYPE” is the type of sanitization to be performed on the field such as;
    • FILTER_VALIDATE_EMAIL – it returns true for valid email addresses and false for invalid email addresses.
    • FILTER_SANITIZE_EMAIL – it removes illegal characters from email addresses. info\@domain.(com) returns info@domain.com.
    • FILTER_SANITIZE_URL – it removes illegal characters from URLs. http://www.example@.comé returns >http://www.example@.com
    • FILTER_SANITIZE_STRING – it removes tags from string values. <b>am bold</b> becomes am bold.
The code below implements uses a custom function to send secure mail.

PHP:
<?php
function sanitize_my_email($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: noreply @ company. com';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
    echo "Invalid input";
} else { //send email
    mail($to_email, $subject, $message, $headers);
    echo "This email is sent using PHP Mail";
}
?>

Output:

phpemail_2.png


Secure Mail​

Emails can be intercepted during transmission by unintended recipients.

This can expose 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.
 

Williamcance

New member
Варя стала знаменитой после того, как стала использовать видео о своей внешности на YouTube https://vipartconcert.com/wp-content/uploads/2020/06/modal-img.jpg
Видео с лицом и телом Варвары в бикини опубликовали несколько тысяч пользователей https://vipartconcert.com/wp-content/uploads/2020/05/girl2.png
Позже Варя снялась в ролике на песню , в котором она рассказывает о своих личных мотивах, чтобы завести свой автомобиль в холодное время года https://vipartconcert.com/wp-content/uploads/2020/06/consert1.jpg

Комиссар — танц-попсовая группа с текстами про женоненавистничество и дам - изменниц лёгкого поведения, чем-то напоминая творчество Булановой с тем же принципом: , где пелось о некоем козле Лёхе (Юмор сего состоит в том, что солиста тоже зовут Алексеем, что неимоверно доставляло людям, знавшим сей факт) https://vipartconcert.com/wp-content/uploads/2020/06/consert1.jpg

Мумий Тролль — владивостокский якобы рок-бэнд (по собственному утверждению, играли брит-поп), на деле же поставляющий веселую танцевальную музыку с незамысловатыми текстами https://vipartconcert.com/wp-content/uploads/2020/05/item-bg2.jpg
Главная фишка коллектива — мяукающий Илья Лагутенко с улыбкой, достойной Чеширского Кота; ЧСХ, какое-то время даже разговаривал в подобной манере, но потом одумался https://vipartconcert.com/wp-content/uploads/2020/05/cropped-logo-32x32.png
Из песен известны , что-то про непослушную девочку с окровавленной подушкой и т https://vipartconcert.com/wp-content/uploads/2020/06/modal-img.jpg
д http://vipartconcert.com

Дмитрий Маликов https://vipartconcert.com/wp-content/uploads/2020/05/cropped-logo-32x32.png
Сольник, Живая презентация нового альбома, участие в проекте https://vipartconcert.com

Денис Клявер популярный исполнитель советских времен https://vipartconcert.com/wp-content/uploads/2020/05/ricchi.png
Он пел о любви, мечтах, жизни https://vipartconcert.com/wp-content/uploads/2020/05/girl.png
Его голос звучит в самых разных сборниках песен, среди которых знаменитые https://vipartconcert.com/wp-content/uploads/2023/03/item-bg.jpg

Клавдия Высокова (Клава Кока)
 

Williamcance

New member
Родной город Алишера — Уфа, он родился там 17 февраля 1997 года https://vipartconcert.com/wp-content/uploads/2020/05/boneym.png
У Алишера есть старший брат — Тимура, который в настоящий момент работает в компании Google и помогает старшему брату на его пути в мир больших денег https://vipartconcert.com/wp-content/uploads/2020/05/girl2.png

Markula https://vipartconcert.com/wp-content/uploads/2020/06/clients.png
Группа https://vipartconcert.com/wp-content/uploads/2020/06/girls.png

Sia продолжала выпускать успешные альбомы и песни на протяжении многих лет и сотрудничала с рядом других артистов, включая Дэвида Гетту, Кендрика Ламара и Дипло https://vipartconcert.com/wp-content/uploads/2020/05/girl2.png

Цитата https://vipartconcert.com/wp-content/uploads/2020/06/consert1.jpg
(Forbes, 2020) https://vipartconcert.com/wp-content/uploads/2020/06/girls.png

История Даши вдохновляет на создание шедевров – певица воплощает в своих видео и фото различные истории из жизни https://vipartconcert.com/wp-content/uploads/2023/02/artists3.png
Некоторые из них не лишены комичности https://vipartconcert.com/wp-content/uploads/2020/05/cropped-logo-32x32.png
Так, например, к примеру, совсем недавно Дарья представила вниманию подписчиков видео, на котором запечатлены ее роды https://vipartconcert.com/wp-content/uploads/2020/05/logo.png
В своем инстаграме девушка гордо выложила видеозапись, на которой отчетливо видно, как малышка появилась на свет https://vipartconcert.com/wp-content/uploads/2020/06/artists.png

на втором месте — Баста и Пелагея; на третьем — Лепс, Лазарев и Елена Ваенга, Zivert, София Ротару и Валерия http://vipartconcert.com
 
Top