How to Send Email Using PHP?

03-Apr-2023

.

Admin

How to Send Email Using PHP?

Hi Dev,

This tutorial is focused on how to send emails in PHP. you'll learn how to send emails using PHP. We will use how to send emails from localhost in PHP. if you have a question about how to send email from localhost using PHP then I will give a simple example with a solution.

Now, let's see the article on how to send emails using PHP. it's a simple example of how to send emails in PHP. you can understand the concept of how to send email from localhost in PHP. if you have a question about how to send email from localhost using PHP then I will give a simple example with a solution.

Example 1: Example of sending plain text in emails


The below example sends the plain text in emails using the PHP mail() function.

<?php

$to = 'youremail@email.com';

$subject = 'Testing Purpose';

$message = 'Hi there, this is the test mail() function?';

$from = 'nicesnippets@email.com';

// Sending email

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

echo 'Your mail has been sent successfully.';

} else{

echo 'Unable to send the email. Please try again.';

}

?>

Note that:- If you are sending mail using Gmail you have to allow non-secure apps to access Gmail you can do this by going to your Gmail settings.

Once less secure apps are enabled; now you can use your Gmail for sending emails.

Example 2: Example of sending HTML in the email using PHP mail()

<?php

$to = 'yourmail@email.com'; // receiver email

$subject = 'Testing Purpose'; // subject

$from = 'nicesnippets@email.com'; // send email

// To send HTML mail, the Content-type header must be set

$headers = 'MIME-Version: 1.0' . "\r\n";

$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Create email headers

$headers .= 'From: '.$from."\r\n".

'Reply-To: '.$from."\r\n" .

'X-Mailer: PHP/' . phpversion();

// Compose a simple HTML email message

$message = '<html><body>';

$message .= '<h1 style="color:#f40;">Hi There!</h1>';

$message .= '<p style="color:#080;font-size:20px;">This is a testing mail?</p>';

$message .= '</body></html>';

// Sending an email to receipt

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

echo 'Your mail has been sent successfully.';

} else{

echo 'Unable to send the email. Please try again.';

}

?>

I hope it could help you...

#PHP