How can I get the correct sender with mail() in PHP? SMTP
If your website sends mail with the PHP function mail(), the mail goes out without logging in. The technical sender (Return-Path) is then often the system account of your package, not your own address. As a result, SPF and DMARC don't line up properly, the mail ends up in spam more often and error messages land in a mailbox nobody checks.
So have your website send mail via SMTP with authentication, just like your mail program does. That way your own address is the sender and the mail is treated as regular mail from your domain.
The SMTP details
- Server: your domain name (yourdomain.nl) if your website is hosted at WebOké, or the server name of your package, such as linux2023.webawere.nl. You can find it in My WebOké under My Products, in the Server column.
- Port: 465 with SSL/TLS, or 587 with STARTTLS.
- Username: the full email address of a mailbox, preferably a separate mailbox for the website, such as website@yourdomain.nl.
- Password: the password of that mailbox.
Use the address of that mailbox as the sender (From), or a forwarder that forwards to it. Never put a visitor's address in From; put it in Reply-To instead. Otherwise the server will reject the mail or it will end up in spam.
Example with PHPMailer
A widely used library is PHPMailer. You install it with Composer (composer require phpmailer/phpmailer).
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// SMTP-instellingen
$mail->isSMTP();
$mail->Host = 'jouwdomein.nl';
$mail->Port = 465;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->SMTPAuth = true;
$mail->Username = 'website@jouwdomein.nl';
$mail->Password = 'wachtwoord';
$mail->CharSet = 'UTF-8';
// Afzender, antwoordadres en ontvanger
$mail->setFrom('website@jouwdomein.nl', 'Website jouwdomein.nl');
$mail->addReplyTo('bezoeker@example.net');
$mail->addAddress('info@jouwdomein.nl');
// Bericht
$mail->Subject = 'Testbericht';
$mail->Body = 'Dit is een testmail verzonden via SMTP.';
$mail->send();
echo 'E-mail verzonden';
} catch (Exception $e) {
echo 'Versturen mislukt: ' . $mail->ErrorInfo;
}
Using WordPress or WooCommerce? Then you can set this up with an SMTP plugin, see Reliably sending mail from WordPress and WooCommerce via SMTP. To learn how to protect a form against spam, read A contact form on your website: emailing fields and preventing spam.
Want to learn more? Take the free course Getting your email in order, lesson 7.3 Mail from your website and forms.
Want to learn more? Take the free WordPress course, lesson 9.1 Email from WordPress.
