Change the From: email address in PHP mail()

Posted on in Categories last updated January 3, 2007

Q. How do I change the email address in PHP mail() function?

A. The php mail() function allows you to send email.

mail() syntax:
bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )

Where,
=> to: Receiver, or receivers of the mail.

=> subject: Subject of the email to be sent.

=> message: Message to be sent.

=> additional_headers: String to be inserted at the end of the email header.
This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n).

string additional_headers is use to specify From: email address in PHP. Generally you write mail() as follows:

<?
$message = "This is a test";
mail([email protected]', 'Subject', $message);
?>

If you would like to add From : email address

Use code as follows:

<?php
$to      = [email protected]';
$subject = 'Subject';
$message = 'This is a test';
$headers = 'From: [email protected]' . "\r\n" .
   'Reply-To: [email protected]' . "\r\n" .
   'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

References

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

15 comment

  1. Is there anyway to solve it in HOTMAIL..

    FROM [email protected] on behalf of email address

    1. ini_set(‘sendmail_from’, ‘[email protected]’);
      if you own the server…or you’ll have to play in the php.ini/call your server/host manager.

  2. if i want to provide the text box for to and from mail ids to the users then what i will do for sending mail from id to To id. I have tried it but i am only able to send mail to the same domain email id’s not all domain email id’s.

  3. I have been looking for a simple example and wasted hours and hours.
    my problem is sending email as follow:
    From [email protected] and all the mails go to junk .

    However, this one sort it nicely as follow:
    From [email protected] and does not goes to junk.

    recommended.

  4. I am new to web development. i want to send mails to different email id’s. Like i am working on a matrimonial site there user can send mails to their matches. But in my case emails are going to a particular email address for a particular user.

Leave a Comment