The Wayback Machine - https://web.archive.org/web/20241004063411/https://www.geeksforgeeks.org/php-sending-mails-using-mail-function/
Open In App

PHP | Sending mails using mail() function

Last Updated : 08 Mar, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

PHP is a server side scripting language that is enriched with various utilities required. Mailing is one of the server side utilities that is required in most of the web servers today. Mailing is used for advertisement, account recovery, subscription etc.

In order to send mails in PHP, one can use the mail() method.

Syntax:

bool mail(to , subject , message , additional_headers , additional_parameters)

Parameters: The function has two required parameters and one optional parameter as described below:

  • to: Specifies the email id of the recipient(s). Multiple email ids can be passed using commas
  • subject: Specifies the subject of the mail.
  • message: Specifies the message to be sent.
  • additional-headers(Optional): This is an optional parameter that can create multiple header elements such as From (Specifies the sender), CC (Specifies the CC/Carbon Copy recipients), BCC (Specifies the BCC/Blind Carbon Copy Recipients. Note: In order to add multiple header parameters one must use ‘\r\n’.
  • additional-parameters(Optional): This is another optional parameter and can be passed as an extension to the additional headers. This can specify a set of flags that are used as the sendmail_path configuration settings.

Return Type: This method returns TRUE if mail was sent successfully and FALSE on Failure.

Examples:

  1. Sending a Simple Mail in PHP




    <?php
      $to = "recipient@example.com";
      $sub = "Generic Mail";
      $msg="Hello Geek! This is a generic email.";
      if (mail($to,$sub,$msg))
          echo "Your Mail is sent successfully.";
      else
          echo "Your Mail is not sent. Try Again.";
    ?> 

    
    

    Output :

    Your Mail is sent successfully.
    
  2. Sending a Mail with Additional Options




    <?php
      $to = "recipient@example.com";
      $sub = "Generic Mail";
      $msg = "Hello Geek! This is a generic email.";
      $headers = 'From: sender@example.com' . "\r\n" .'CC: another@example.com';
      if(mail($to,$sub,$msg,$headers))
          echo "Your Mail is sent successfully.";
      else
          echo "Your Mail is not sent. Try Again.";
    ?> 

    
    

    Output :

    Your Mail is sent successfully.
    

Summary:

  • Using mail() method one can send various types of mails such as standards, html mail.
  • The mail() method opens the SMTP socket, attempts to send the mail, closes the socket thus is a secure option.
  • mail() method should not be used for bulk mailing as it is not very cost-efficient.
  • The mail() method only checks for parameter or network failure, thus a success in the mail() method doesn’t guarantee that the intended person will receive the mail.


Similar Reads

How to write e-mails in HTML and send it using Gmail ?
In this article, we are going to learn that how users can write e-mails in HTML format and send them using Gmail. However, Gmail doesn't offer an HTML editor still we can send HTML templates in an e-mail using some tools and methods. Many people need to send an e-mail with HTML templates to others. By using the below methods, users will be able to
3 min read
How to configure XAMPP to send mail from localhost using PHP ?
To configure XAMPP server to send mail from localhost we have to make changes to two files sendmail.ini and php.ini. Open the xampp folder. By the name of "sendmail.ini" is present in sendmail file and "php.ini" is present in php file in the xampp folder. Step 1: Go to C:\xampp\sendmail: open sendmail.ini file in notepad or any text editor and make
2 min read
Sending bulk emails in Node.js using SendGrid API
What is SendGrid API? SendGrid is a platform for sending transactional and marketing emails to the customers. It provides scalability, reliability, and deliverability which is an important issue for an organization.Benefits of using SendGrid API: If you are using Nodemailer with Gmail then you can send only certain amount of emails per day.Also, th
2 min read
Sending SMS using NEXMO API in Node.js
Introduction: SMS is a common method of sending short messages between cell phones, but these SMS can be sent using API in Node.js. Now there are lots of API in the market for sending SMS like Twilio, Exotel, etc to the user but the popular among them is Nexmo. Features of NEXMO: Integrating this module in your code is very simple and efficient. Us
2 min read
Sending bulk SMS in Node.js using Twilio
SMS is a common method of sending short messages between cell phones, but these SMS can be sent to multiple users at a time using Twilio notify service. Sending bulk SMS to users at a time is possible using Twilio. Introduction: It's easy to get started and easy to use. It is widely used for sending bulk SMS. User can send SMS to desired mobile num
2 min read
Sending HTTP Request Using cURL Set-1
Whenever we are dealing with HTTP requests, cURL simplifies our tasks to a great extent and is the easiest tool to get our hands dirty on. cURL: It stands for "client URL" and is used in command line or scripts to transfer data. It is a great tool for dealing with HTTP requests like GET, POST, PUT, DELETE, etc. Although it provides us with the supp
3 min read
Sending Push Notifications : Progressive Web Apps
We need permissions to send push notifications. Key Points : Notifications must be timely. Should be precise (contains all the information a user needs). Should be relevant to the user. Basic Example : An airline app must send push notifications such as "Your flight will be boarding from..." Browser that supports push notifications are : Chrome 44
3 min read
Explain the common methods of sending request to a server in jQuery
In this article, we will see the common methods of sending requests to a server by using the jQuery library. jQuery is an open-source JavaScript library jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animation, Ajax interactions cross-browser JavaScript development. Common methods of Sending Requests to the
3 min read
Why are HTTP cookies used by Node.js for sending and receiving HTTP cookies?
The HTTP protocol is one of the most important protocols of the Application layer of the OSI model. The main use of this protocol is for sending hypertext information to the client to the server and server to the client to communicate on the World Wide Web. But, the HTTP protocol is a stateless protocol which means that this protocol cannot maintai
5 min read
How to define the HTTP method for sending data to the action URL in HTML5?
In this article, we will learn how to define an HTTP method to send data to the action URL. The method attribute is used to indicate how form data can be sent to the given server in the action URL. The form-data may be sent using the GET or POST method depending on the requirement. The differences between the GET and POST method are defined below:
2 min read
How to check if an email address exists without sending an email ?
In this article, we will learn to check if an address exists without sending an email. Approach: By using some free APIs we can easily check whether an email is valid or not. One of the easiest way to check whether an email address is valid is to use PHP's filter_var() function. Example 1:The following method can only check if the format is a valid
3 min read
Sending Command Line Arguments to NPM Script
In the sector of NodeJS development, NPM (Node Package Manager) scripts are a effective tool for automating numerous tasks like strolling exams, building the mission, or starting a improvement server. However, there are times while you need to bypass arguments to these scripts to customize their behavior. This article will discover how you can ship
3 min read
Creating and Sending an XML Document in JQuery
Creating and sending XML documents with jQuery is a common task in web development, particularly for API or web service interactions that require XML format. This article explores different strategies to efficiently construct, modify, and dispatch XML documents using jQuery. Table of Content Using jQuery's .ajax() Method with an XML StringBuilding
4 min read
How to Use Postman for Sending POST Requests?
Understanding how to send a POST request in Postman is a crucial skill for any developer or tester. POST requests are typically used for submitting data to a server, such as creating new resources or uploading files. What is a POST Request?A POST request is an HTTP request method used for sending data to a target server. In RESTful APIs, POST reque
4 min read
How to connect Skype, Mail and Phone using HTML ?
Connecting to Mail: Mailto link is a default way to sending a mail when the consumer wants to communicate or wants to give feedback, then by clicking the mailto link will open a default sending mail window. So we can use mailto which direct to the mail once the form is submitted. Using mailto we can set the action field of the form and in this case
3 min read
Difference between Web Server and Mail Server
Web Server : Web Server, as the name suggests, is a server software where web content is stored and uses HTTP protocol and other protocols to respond to user requests that is being made over WWW. Its main function is to display the content of the website through storing, processing, and delivering webpages within the website to users. Example: Apac
4 min read
What is the use of Post via e-mail option in WordPress Writing Setting ?
The "Post via e-mail" option in WordPress allows you to post to your WordPress blog by email. This can be useful if you want to post to your blog while you are away from your computer, or if you prefer to compose your posts in a text editor or email client instead of in the WordPress editor. To use this feature, you will need to set up a secret ema
5 min read
How to create mail and phone link in HTML ?
We will go through the step-by-step process of creating HTML Mailto and Call links. These links are useful for improving user interaction on your website, allowing users to quickly contact you via email or phone with a simple click. Creating a Mailto LinkA mailto link is an easy way for users to contact website owners or anyone else directly from a
3 min read
How to Send a User Verification Mail in Web and Firebase ?
In this article, we will see how to send the user verification email to the user, so that only verified users can be signed In to their account using Email Password Authentication. The Drawback of email password authentication is that, when a user signs up using an arbitrary email, firebase allows them to sign up and sign in, Unlike email is arbitr
2 min read
How the User-Defined Function differs from Built-in Function in PHP ?
In PHP, functions are blocks of reusable code that perform specific tasks. They enhance code readability, modularity, and maintainability by encapsulating logic into named units. PHP functions can be categorized into two main types: user-defined functions and built-in functions. User-Defined FunctionsUser-defined functions are functions created by
2 min read
PHP | Program to delete an element from array using unset() function
Given an array of elements, we have to delete an element from the array by using the unset() function. Examples: Input : $arr = array("Harsh", "Nishant", "Bikash", "Barun"); unset($arr[3]); Output : Array ( [0] => Harsh [1] => Nishant [2] => Bikash ) Input : $arr = array(1, 2, 6, 7, 8, 9); unset($arr[3]); Output : Array ( [0] => 1 [1] =
2 min read
How to delete text from file using preg_replace() function in PHP ?
Given a file containing some elements and the task is to delete the content of the file using preg_replace() function. The preg_replace() function is searches the string pattern in the file and if string pattern found then it replace with the required string. In simple words it can modify the contents of a file. Syntax: preg_replace( $pattern, $rep
2 min read
How to Detect Character Encoding using mb_detect_encoding() function in PHP ?
Character encoding is an essential aspect of handling text in various programming languages including PHP. Different character encodings such as UTF-8, ISO-8859-1, and ASCII represent characters differently. Finding the correct character encoding of text is important to ensure proper data processing and display. In PHP, the mb_detect_encoding() fun
2 min read
PHP 5 vs PHP 7
PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994. Since its launch in 1994 PHP has become an industry standard supporting almost 80% of the websites ( 79.8% to be precise) with its closest competitor being ASP.Net at 19.8% and others like Ruby, Java trailing far behind. The PHP development team released
4 min read
How to include content of a PHP file into another PHP file ?
Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file
2 min read
What is New in PHP Type Hinting Support in PHP 8?
PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently. These are the following features used in PHP Type Hitting Support: Table of Content Union TypesMixed TypeStatic Return TypeInheritance of Contravariant ParametersInheritance of P
3 min read
Build an E-Commerce Web Application using HTML CSS PHP and hosted using XAMPP
In this article, we will see know how to develop a simple e-commerce Web application that offers a seamless and user-friendly experience for customers, allowing them to register and login into their accounts,  easily browse for products, add items to their cart, and also allow them to add their delivery address, with the help of HTML, CSS & PHP
11 min read
How to submit a form without using submit button using PHP ?
In this article, we will see how to submit the form without clicking the submit button, along with understanding the different ways to accomplish this task through implementation. The form can be submitted without using submit button by implementing a specific event attribute or by clicking the link. This task can be done by using the OnClick event
3 min read
How to get the function name from within that function using JavaScript ?
Given a function and the task is to get the name of the function from inside the function using JavaScript. There are basically two methods to get the function name from within that function in JavaScript. These are: Using String substr() MethodUsing Function prototype name propertyGet the Function name using String substr() MethodThis method gets
2 min read
How to implement a function that enable another function after specified time using JavaScript ?
Let us assume that we have been given a function add() which takes in two parameters a and b, and returns their sum. We are supposed to implement a function that should be able to call any function after the given delay amount of time. This can be done with the approaches as given below: Approach 1: Create a function that takes in the amount of del
2 min read