Search code examples
phpemailphpmailer

Phpmailer, can't set needed 'from' email


This code is work, email is sent

$mail = new PHPMailer();

$mail->setFrom("name1@gmail.com", "Name");

$mail->addAddress($to); //Recipient name is optional

//Address to which recipient will reply
$mail->addReplyTo("name1@yahoo.com", "Reply");

//Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = $subject;
$mail->Body = $body;

if(!$mail->send())
    {
         echo 'Mailer Error: ' . $mail->ErrorInfo . "\n";
    }

But for some reason, if I change From email to name2@yahoo.com

    $mail->setFrom("name2@yahoo.com", "Name");

emails does not sends anymore. Phpmailer does not report any error messages.

name2@yahoo.com is valid working email address related to this web server.

Thanks.


Solution

  • This is covered in the PHPMailer troubleshooting guide.

    Most service providers now have strict SPF and DMARC configurations (Yahoo especially, since they invented DMARC) that mean that you cannot send from addresses in their domains except through their own mail servers, or any others included in their SPF records.

    Your code is sending through your own local server, which is not a Yahoo server, and thus won't work.

    The solution is to send through Yahoo's own servers using authentication for your email account, something like:

    $mail->isSMTP();
    $mail->Host = 'smtp.mail.yahoo.com';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;
    $mail->Username = 'me@yahoo.com';
    $mail->Password = 'password';
    

    Yahoo's DMARC config won't let you spoof the from address, so you can only use a from address that matches your username - this is probably the cause of the symptom you're seeing.