Email Function

Sending Emails

PHP has a built-in function called mail() that allows you to send emails directly from a script.

Here's a basic example:

<?php
$to = "someone@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";

mail($to,$subject,$txt,$headers);
?>

In the above example, the mail() function takes four arguments: the recipient's email, the email subject, the email body text, and additional headers like 'From' or 'CC'.

Here's a more advanced example that sends an HTML email:

<?php
$to = "someone@example.com";
$subject = "My HTML email";
$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

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

In this example, the Content-type header is set to text/html to indicate that the email content should be interpreted as HTML.

Please note that the PHP mail() function requires your server to be configured to send mail. This usually involves setting up an SMTP server, and the configuration details can vary depending on your hosting environment.

Last updated