How To Send An Email In PHP



Sending emails programmatically is a common task in web development, especially when building applications that require user communication or notifications. In PHP, you have several methods to accomplish this, including using the built-in mail function or integrating a third-party SMTP (Simple Mail Transfer Protocol) library for more advanced email handling.

In this article, we will explore how to send an email in PHP using both the mail function and SMTP. We will also cover topics such as composing email messages, adding file attachments, including CC and BCC recipients, sending HTML emails, and handling delivery errors. By the end of this tutorial, you’ll have a solid understanding of how to incorporate email functionality into your PHP projects.

Before diving into the implementation details, it’s important to have a basic understanding of PHP and web development concepts. Familiarity with HTML, CSS, and basic PHP syntax is assumed throughout this guide. Additionally, you should have a development environment set up with PHP and a web server installed, such as Apache or Nginx.

Now, let’s proceed to the next section to see how we can set up the PHP mail function to send emails.



Before we start sending emails in PHP, there are a few prerequisites you need to have in place. Here are the essential requirements:

1. Web Server: You need a web server installed on your local machine or hosting environment to run PHP scripts. Apache, Nginx, or XAMPP are popular choices.

2. PHP: Ensure that you have PHP installed on your system. You can download the latest version of PHP from the official website ( and follow the installation instructions for your operating system.

3. SMTP Server (Optional): If you want to use SMTP to send emails, you will need access to an SMTP server. There are multiple options available, such as Gmail, SendGrid, or Mailgun. Sign up for an account with your chosen provider and obtain the SMTP credentials (host, port, username, password) required for the configuration.

4. Text Editor or Integrated Development Environment (IDE): Use a text editor or an IDE that supports PHP for writing and editing your PHP scripts. Popular choices include Visual Studio Code, Sublime Text, and PHPStorm.

5. Familiarity with HTML and CSS: Having a basic understanding of HTML and CSS will be helpful when creating the email content. You can style the email using inline CSS or include a separate CSS file.

With these prerequisites in place, you’re now ready to proceed with setting up the PHP mail function or integrating an SMTP library for sending emails. In the next section, we’ll explore the steps involved in configuring the PHP mail function.


Setting up the PHP mail function

The PHP mail function allows you to send emails directly from your server without relying on external libraries or services. To start using the mail function, follow the steps outlined below:

1. Configure the PHP.ini file: Open your PHP.ini file and locate the [mail function] section. Make sure the following settings are correctly configured:

  • SMTP: Set the SMTP server address. For example, you can use “”.
  • smtp_port: Define the port number for the SMTP server. Typically, port 25 is used for unencrypted connections, and port 587 is used for encrypted connections.
  • sendmail_from: Set the email address that will appear as the sender of the emails.

2. Restart your web server: After modifying the PHP.ini file, restart your web server to apply the changes.

3. Test the mail function: To ensure the mail function is working correctly, create a simple PHP script that sends a test email. Here is a basic example:

$to = "";
$subject = "Test Email";
$message = "This is a test email sent using the PHP mail function.";

$headers = "From:" . "\r\n" .
    "Reply-To:" . "\r\n" .
    "X-Mailer: PHP/" . phpversion();

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "Failed to send email.";

Note: Replace “” and “” with the appropriate email addresses.

Save the script with a .php extension and run it in your web browser. If the email is sent successfully, you should see the “Email sent successfully!” message.

With the PHP mail function configured and tested, you can now move on to exploring more advanced techniques, such as sending emails via SMTP or adding file attachments. We’ll cover these topics in the upcoming sections.


Using SMTP to send emails

While the PHP mail function is a simple way to send emails, it has some limitations, such as difficulty handling authentication, encryption, and delivery status tracking. To overcome these limitations, you can use SMTP (Simple Mail Transfer Protocol) to send emails from your PHP application. SMTP provides more robust functionality and allows you to connect to an external SMTP server to send your emails.

To configure and use SMTP in PHP, follow these steps:

1. Choose an SMTP server: There are various SMTP providers available, such as Gmail, SendGrid, or Mailgun. Select the provider that best suits your needs and sign up for an account.

2. Obtain SMTP credentials: Once you have an account with an SMTP provider, they will provide you with the necessary credentials to connect to their SMTP server. These credentials typically include the SMTP server address, port number, username, and password.

3. Set up a PHP library: To simplify the process of sending emails via SMTP in PHP, you can use a PHP library like PHPMailer or SwiftMailer. These libraries provide convenient methods and classes to handle sending emails with SMTP authentication and other advanced features.

4. Install and configure the PHP library: Install the chosen PHP library using Composer or by manually including the library files in your project. Follow the library’s documentation to configure it with your SMTP credentials.

5. Compose and send an email using SMTP: Now you’re ready to start sending emails with SMTP. Use the library’s API to compose the email message, set the recipient, subject, body, and any additional headers, and send the email using the SMTP transport option.

Using SMTP to send emails provides greater flexibility and control over the email sending process. You’ll also benefit from enhanced security features, such as encryption and authentication, ensuring that your emails are delivered reliably and securely.

In the next section, we’ll dive into the details of composing the email message in PHP, including the subject, body, and headers.


Composing the email message

When sending an email in PHP, it’s important to compose the email message with the necessary components, such as the recipient(s), subject, body, and any additional headers. Let’s explore each of these components in detail:

1. Recipients: Specify the email addresses of the recipients using the “To” field. You can also include multiple recipients by separating their addresses with commas.

2. Subject: Set the subject line of the email using the appropriate field. Make the subject concise and descriptive to give recipients a clear idea of the email’s content.

3. Body: The body of the email contains the main content or message you want to convey to the recipients. It can be plain text or HTML formatted.

If you choose plain text, you can simply assign the text content to a variable. For example:

$message = "Hello, this is the body of the email.";

If you want to send HTML formatted emails, you need to construct the email body using HTML tags. For example:

$message = "<html><body><h1>Hello</h1><p>This is the body of the email.</p></body></html>";

Note: When sending HTML emails, it’s essential to properly construct the HTML structure, including the necessary tags and inline CSS for styling. Ensure the email is designed to be mobile-friendly and accessible.

4. Additional headers: Headers provide additional instructions or information to the email server and recipients. For example, you can include the “Reply-To” header to specify the email address where replies should be directed.

To add additional headers, you can use the concatenation operator (“.”) to build a header string. Here’s an example:

$headers = "From:" . "\r\n";
$headers .= "Reply-To:" . "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();

Once you have constructed the necessary components of the email message, you can use either the PHP mail function or an SMTP library to send the email. We will cover both approaches in the following sections.

Now that you understand how to compose the email message, let’s move on to the next section, which covers adding file attachments to emails.


Adding file attachments

Email attachments allow you to include files, such as images, documents, or PDFs, along with your email message. In PHP, you can easily add file attachments to your emails, whether you’re using the PHP mail function or an SMTP library. Here’s how you can add file attachments to your emails:

1. Prepare the file: Before attaching a file to an email, make sure the file is accessible on your server or local machine. Determine the file’s full path or use a file upload mechanism to obtain the file.

2. Encode the file for email: To attach the file, you need to encode it using the MIME (Multipurpose Internet Mail Extensions) format. This encoding process ensures that the file is sent correctly as part of the email. You can use the appropriate PHP functions, such as base64_encode(), to encode the file content.

3. Set the appropriate headers: When adding file attachments, you need to include specific headers to indicate the attachment’s content type, disposition, and filename. These headers help the recipient’s email client recognize and handle the attachment correctly.

Here’s an example of how to attach a file using the PHP mail function:

$to = "";
$subject = "Email with Attachment";
$message = "This email includes an attachment.";

$file_path = "/path/to/file.pdf";
$file_content = file_get_contents($file_path);
$file_encoded = base64_encode($file_content);

$attachment = chunk_split($file_encoded);

$mime_boundary = "-----=" . md5(uniqid(microtime(), true));

$headers = "From:" . "\r\n";
$headers .= "Reply-To:" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $mime_boundary . "\"" . "\r\n";

$email_body = "--" . $mime_boundary . "\r\n";
$email_body .= "Content-Type: text/plain; charset=\"UTF-8\"" . "\r\n";
$email_body .= "Content-Transfer-Encoding: 7bit" . "\r\n\r\n";
$email_body .= $message . "\r\n\r\n";
$email_body .= "--" . $mime_boundary . "\r\n";
$email_body .= "Content-Type: application/pdf; name=\"" . basename($file_path) . "\"" . "\r\n";
$email_body .= "Content-Disposition: attachment; filename=\"" . basename($file_path) . "\"" . "\r\n";
$email_body .= "Content-Transfer-Encoding: base64" . "\r\n\r\n";
$email_body .= $attachment . "\r\n\r\n";
$email_body .= "--" . $mime_boundary . "--";

mail($to, $subject, $email_body, $headers);

Make sure to replace “”, “”, and “/path/to/file.pdf” with the appropriate email addresses and file path, respectively.

Adding file attachments to your emails enhances communication by allowing you to share relevant information with recipients. Next, we’ll discuss how to include CC and BCC recipients in your emails.


Adding CC and BCC recipients

In addition to including a primary recipient in your emails, you may also want to send copies of the email to other recipients for their information or for discreet communication. PHP provides the functionality to add CC (Carbon Copy) and BCC (Blind Carbon Copy) recipients to your emails. Here’s how you can include CC and BCC recipients in your emails:

1. CC Recipients: CC recipients receive a copy of the email and are visible to all other recipients. You can add CC recipients by including their email addresses in the “CC” header. Separate multiple CC recipients with commas.

For example:

$to = "";
$cc = ",";
$subject = "Email with CC Recipients";
$message = "This email includes CC recipients.";

$headers = "From:" . "\r\n";
$headers .= "CC: " . $cc . "\r\n";

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

2. BCC Recipients: BCC recipients also receive a copy of the email, but their email addresses are not visible to other recipients. To add BCC recipients, include their email addresses in the “BCC” header. Similar to CC recipients, separate multiple BCC recipients with commas.

For example:

$to = "";
$bcc = ",";
$subject = "Email with BCC Recipients";
$message = "This email includes BCC recipients.";

$headers = "From:" . "\r\n";
$headers .= "BCC: " . $bcc . "\r\n";

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

When adding CC and BCC recipients, ensure that you respect privacy and adhere to legal regulations regarding email communication. Be mindful of sharing sensitive information and always obtain consent from recipients before including them in CC or BCC fields.

Including CC and BCC recipients in your emails enables effective communication with multiple stakeholders while maintaining privacy when necessary. Next, we’ll discuss how to send HTML emails in PHP.


Sending HTML emails

In PHP, you have the ability to send emails in HTML format, allowing for more visually appealing and dynamic content. HTML emails enable you to include formatted text, images, links, and even interactive elements within your email messages. Here’s how you can send HTML emails in PHP:

1. Create the HTML content: Construct the HTML content that you want to include in your email. You can use HTML tags to structure the layout, apply styling with inline CSS, and insert dynamic data using PHP variables. Make sure to test the HTML content in various email clients and devices to ensure it renders correctly.

For example:

$to = "";
$subject = "HTML Email Example";
$message = "<html><body><h1>Hello, recipient!</h1><p>This is an example of an HTML email sent via PHP.</p></body></html>";

$headers = "From:" . "\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8" . "\r\n";

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

2. Set the Content-Type header: To indicate that your email contains HTML content, include the “Content-Type” header in the email headers. Set the value of the header to “text/html” to inform the recipient’s email client that the email should be interpreted as HTML.

Note: It’s important to include the correct charset in the Content-Type header to ensure proper character encoding.

By sending HTML emails, you have the flexibility to create visually appealing and engaging content that can enhance the user experience. However, keep in mind that not all email clients support HTML, and some email clients may strip or modify certain CSS styles. Therefore, it’s recommended to thoroughly test your HTML emails across different email clients to ensure consistent rendering.

In the following section, we’ll discuss how to handle email delivery errors and gracefully handle any issues that may arise during the sending process.


Handling email delivery errors

While sending emails in PHP, there may be instances where the delivery of an email fails due to various reasons such as invalid recipient addresses, network issues, or exceeded email sending limits. It’s important to handle these email delivery errors gracefully to provide feedback to the user and to troubleshoot any potential issues. Here are some recommended practices for handling email delivery errors in PHP:

1. Check the return value: When using the PHP mail function, it returns a boolean value indicating the success or failure of the email sending process. You can use this return value to check if the email was sent successfully or encountered an error.

For example:

$to = "";
$subject = "Email with Error Handling";
$message = "This email includes error handling.";

$headers = "From:" . "\r\n";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully!";
} else {
    echo "Failed to send email.";

2. Log error messages: In case of email delivery failures, logging the error messages can help in troubleshooting and identifying the root causes. You can use PHP’s error logging functions, such as error_log(), to record the error messages in a log file or database.

3. Provide user feedback: If an email fails to send, it’s important to provide clear feedback to the user. This can be done by displaying an informative message on the website or application interface, informing the user about the issue and possible reasons for the failure.

4. Validate recipient addresses: Before sending an email, validate the recipient addresses to ensure they are properly formatted and exist. You can use regular expressions or PHP’s built-in validation functions, such as filter_var(), to validate email addresses.

5. Monitor email delivery status: Implement mechanisms to monitor the delivery status of sent emails. Some email service providers offer built-in delivery status tracking or webhooks that can notify you about bounced emails, spam complaints, or other delivery issues. By monitoring the delivery status, you can take appropriate action and ensure the reliability of your email communication.

By implementing these practices, you can effectively handle email delivery errors and improve the overall success rate of your sent emails. It’s important to continuously monitor and optimize your email sending process to ensure deliverability and a seamless user experience.

In the next section, we’ll conclude this article by summarizing the key points covered and emphasizing the importance of email communication in PHP development.



In PHP development, the ability to send emails programmatically opens up a wide range of possibilities for communication and notification functionalities within web applications. Whether you choose to use the built-in PHP mail function or integrate an SMTP library, understanding the various aspects of email sending is crucial for successful implementation.

In this article, we covered the prerequisites for sending emails in PHP, including having a web server, PHP installed, and optionally an SMTP server. We discussed setting up the PHP mail function and configuring the PHP.ini file to enable seamless email sending. Additionally, we explored the option of using SMTP to overcome limitations and enhance email handling.

We also delved into composing email messages, including the recipient(s), subject, body, and additional headers. We highlighted the importance of constructing HTML emails for visually appealing and interactive content. Furthermore, we covered advanced techniques such as adding file attachments, including CC and BCC recipients, and handling email delivery errors gracefully.

By following best practices, such as validating recipient addresses, logging error messages, and providing user feedback, you can ensure a seamless email sending experience in your PHP applications. Regularly monitoring email delivery status and optimizing your email sending process will contribute to improved deliverability and reliability.

Email communication remains a vital component in web development, enabling effective user engagement, notifications, and information sharing. Whether it’s sending transactional emails, newsletters, or user notifications, mastering the art of email sending in PHP is a valuable skill to have.

By incorporating email functionality into your PHP projects, you can enhance user experience, foster better communication, and provide valuable information to your users. With the knowledge gained from this article, you are well-equipped to implement robust email sending capabilities in your PHP applications.

Leave a Reply

Your email address will not be published. Required fields are marked *