How to send an email with PHP
Sending an email with PHP is a common task that can be easily accomplished using the built-in mail() function.
Here’s a basic example:
$to = "recipient@example.com"; $subject = "Test email"; $message = "This is a test email"; $headers = "From: sender@example.com"; mail($to, $subject, $message, $headers);
In the above example, we define the recipient email address in the $to variable, the subject of the email in the $subject variable, and the message body in the $message variable. We also specify the sender’s email address in the $headers variable.
Once we have these variables defined, we simply call the mail() function, passing in the appropriate arguments. The function will then send the email.
Here’s another example that includes additional headers:
$to = "recipient@example.com"; $subject = "Test email"; $message = "This is a test email"; $headers = "From: sender@example.comrn"; $headers .= "Reply-To: sender@example.comrn"; $headers .= "Cc: another@example.comrn"; $headers .= "Bcc: hidden@example.comrn"; mail($to, $subject, $message, $headers);
In this example, we’re including the sender’s email address in the From header, as well as specifying a Reply-To email address, and including additional recipients in the Cc and Bcc headers.
For more information about the mail() function and its options, see the official PHP documentation.
Written by: Maria Jensen 17-06-2023 Written in: PHP tutorials