Changing the `from` address when sending an email

2019-08-11 08:33发布

问题:

I'm trying to use PHP Pear Factory to send emails through GMail in one project. It has been successful, but there is something that is not working 100% properly.

I don't know why if I set $headers['From'] = 'from@domain.com', when I receive the email the From is username@gmail.com.

Find below the code:

$recipients = 'to@domain.com';

$headers['From']    = 'from@domain.com';
$headers['To']      = 'to@domain.com';
$headers['Subject'] = 'Test message';

$body = 'Test message';

$params["host"] = 'ssl://smtp.gmail.com';
$params["port"] = 465;
$params["auth"] = true;
$params["username"] = 'username@gmail.com';
$params["password"] = 'password';


// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory('smtp', $params);

$send = $mail_object->send($recipients, $headers, $body);

if(PEAR::isError($send)) { print($send->getMessage()); }

回答1:

In my own experience, GMail only allows the FROM header to be your own GMail account/address. When I tried to get it working with an address different from that, I couldn't manage to send out the email.



回答2:

You just need to authorize the from address in Gmail.

To do that from your Gmail inbox:

  1. Click the gear icon and pick Settings.
  2. On the Accounts and Imports tab click the Add another email address you own link.
  3. Enter your info and pick Next Step.
  4. Pick Send through Gmail (easier to set up) and pick Next Step.
  5. Click Send Verification.
  6. Click the link in the email you added.
  7. Send mail from that from address!