Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to send an email

Short answer

The built-in mail() function sends an email through the server's mail program:

<?php
 
// send.php
 
$sent = mail('anna@example.com', 'Welcome', 'Thank you for signing up.', [
    'From' => 'site@example.com',
    'Content-Type' => 'text/plain; charset=utf-8',
]);
 
echo $sent ? 'Sent' : 'Failed';

Over SMTP

Emails from mail() often land in spam. Sending over SMTP with PHPMailer (composer require phpmailer/phpmailer) is more reliable:

<?php
 
// send.php
 
require 'vendor/autoload.php';
 
$mail = new PHPMailer\PHPMailer\PHPMailer(true);
 
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = getenv('MAIL_USER');
$mail->Password = getenv('MAIL_PASSWORD');
$mail->CharSet = 'UTF-8';
 
$mail->setFrom('site@example.com', 'Site');
$mail->addAddress('anna@example.com');
$mail->Subject = 'Welcome';
$mail->Body = 'Thank you for signing up.';
 
$mail->send();

Functions used in this recipe

  • mail — Sends an email through the server's mail program.
  • filter_var — Validates or sanitises a value by a given rule.
  • error_log — Writes a message to the error log.

Thanks for reading!

Donate to the site — we work hard for you.