Send Email With PHP

Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP.

send email with php

So, you want to send automated email messages from your PHP application. This can be in direct response to a user’s action, such as signing up for your site, or a recurring event at a set time, such as a monthly newsletter. Sometimes email contains file attachments, both plain text and HTML portions, and so on. To understand how to send each variation that may exist on an email, we will start with the simple example and move to the more complicated.

Note that to send email with PHP you need a working email server that you have permission to use: for Unix machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in your php.ini file to point to your email server.

Sending a Simple Text Email

Following example will send a simple TExt email message to someaddress@example.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.

$to = 'someaddress@example.com';
$subject = 'Otallu Test E-mail';
$message = "Hello World! \n\n This is simple plain text mail.";
$headers = "From: abc@example.com \r\n";

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

echo $mail_sent ? "E-Mail sent!" : "Sending E-Mail failed";

Sending an HTML Email

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.

Following example will send an HTML email message to someaddress@example.com. You can code this program in such a way that it should recieve all content from the user and then it should send an email.

$to = 'someaddress@example.com';
$subject = 'Otallu Test E-mail';

$message = "<h2>Hello World!</h2>";
$message .= "<p>This is something with <b>HTML</b> formatting.</p>";

$headers = "From: SomeName <abc@example.com> \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

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

echo $mail_sent ? "E-Mail sent!" : "Sending E-Mail failed";

Function Used: