Search code examples
phpphpmailer

Sending mails with different address as compared to the one used for smtp


I am trying to use phpmailer for sending mails. The mail is being sent but I am unable to change the from address.


try {
    //Server settings
    $mail->SMTPDebug = 2;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = '[email protected]';                     // SMTP username
    $mail->Password   = '****';                               // SMTP password
    $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]');
    $mail->addAddress('[email protected]' );     // Add a recipient
    // $mail->addAddress('[email protected]');               // Name is optional
    // $mail->addReplyTo('[email protected]', 'Information');
    // $mail->addCC('[email protected]');
    // $mail->addBCC('[email protected]');

    // Attachments
    // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

When the mail is being sent the from address happens to be [email protected] i.e. the one used in the smtp settings and not the one I have entered in mail->setFrom().How do i fix this?


Solution

  • This is a well-known issue that's covered in the PHPMailer docs - gmail does not allow you to send from arbitrary addresses because it's forgery. On top of that, Yahoo's DMARC policy is set to 'reject', so even if gmail allowed you to send from a yahoo address, any receiving server would reject the message anyway.

    So the answer here is, no, you can't do this. If you want to send from a yahoo address, you must send through a Yahoo server.