How do I get the correct sender with mail() in PHP? SMTP
If you use PHP's mail() function, the sender will be accountname@yourdomain.xx. This cannot be changed and will cause errors or result in the email being treated as spam.
It is best to use SMTP. There are many free PHP classes for this available online. The email is then sent via SMTP and the sender can easily be set.
A popular option is PHPMailer
You can also use PEAR Mail to send email directly via SMTP. This is especially useful for forms or custom scripts.
https://pear.php.net/package/Mail
https://pear.php.net/package/Net_SMTP
https://pear.php.net/package/Auth_SASL
Example: sending SMTP mail with PEAR
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
// PEAR Mail laden
require_once 'Mail.php';
// SMTP-instellingen
$smtp_host = 'ssl://mail.server.tld';
$smtp_port = 465;
$smtp_user = 'user@domein.nl';
$smtp_pass = 'wachtwoord';
// E-mailgegevens
$to = 'ontvanger@domein.nl';
$from = 'user@domein.nl';
$subject = 'Testbericht';
$body = 'Dit is een testmail verzonden via SMTP.';
$reply = 'user@domein.nl';
// Headers
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject,
'Reply-To' => $reply
);
// SMTP object
$smtp = Mail::factory('smtp', array(
'host' => $smtp_host,
'port' => $smtp_port,
'auth' => true,
'username' => $smtp_user,
'password' => $smtp_pass
));
// Mail verzenden
$result = $smtp->send($to, $headers, $body);
if (PEAR::isError($result)):
echo $result->getMessage();
else:
echo 'E-mail succesvol verzonden';
endif;
