Reputation: 14398
I'm using PHPMailer linked to my gmail account.
I've required the autoloader, created a function to handle sending mail, then fire the function to test. It all looks like this:
require "PHPMailer/PHPMailerAutoload.php";
function sendMail($to, $subject, $body, $from){
//init PHPMailer
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->isHTML(true);
//connection settings
$mail->Host = "smtp.gmail.com";
$mail->Username = "[email protected]";
$mail->Password = "xxxxxxxx";
//addresses
$mail->addAddress($to);
$mail->setFrom($from);
//create email
$mail->Subject = $subject;
$mail->Body = $body;
//send email
$mail->send();
}
//sendMail(to, subject, body, from)
sendMail("[email protected]", "Test Subject", "Test body", "[email protected]");
This sends the email with the correct subject and body, to the right place, but it ignores the 'from' address and the email always says it comes from the gmail account through which the email is passed. Is there anyway to configure this to work?
Note I have obviously omitted the correct account details and real to or from addresses from the code above.
Upvotes: 0
Views: 5550
Reputation: 37710
It's very simple: By default, Gmail doesn't allow you to set the from address to a non-gmail address unless they are handling your domain; they will rewrite the from address to be your gmail address, exactly as you are seeing. This is nothing to do with PHPMailer nor the PHP mail function.
There is provision to set up specific from addresses (rather than whole domains), but you have to set them up beforehand; you can't just send from random addresses. See this answer.
Upvotes: 5
Reputation: 571
Change mentioned portion below:
$mail->addAddress($to);
$mail->setFrom($from);
TO
$mail->addAddress($to);
$mail->From = $from;
$mail->FromName = $from_name;
Hope it will work.
Regards.
Upvotes: -1