Sending email using PHP is a pretty straightforward task and this short how to will show you exactly how to do that. The key to sending emails in PHP is the mail() function. Here’s how to to use it:
// example number 1 – the basic
mail("email@address.com",
"subject of message",
"body of message");
<span id="more-45"></span>
// example number 2 – two recipients and specifying email sender
mail("email@address.com,email@address.net",
"subject of second message",
"body of message",
"From: sender@email.com\r\n");
// example number 3 – specifying sender and CC recipient
mail("email@address.com",
"subject of second message",
"body of message",
"From: sender@email.com\r\nCC: email@address.net\r\n");
?>
The mail function accepts at least three parameters namely the recipient, subject and the message. That alone will do most of what you need to do. The power however of the mail() function is in the option fourth parameter which is for adding additional headers. It accepts a string which can contain any valid email header. The second example above shows how to use the fourth header to specify the sender of the email but it can do more than that.
You can specify CC or BCC recipients in it and if you’re up for the challenge, you can use it to add attachments to your email. Yes, I know that’s tough and that really sucks knowing that other scripting languages such as ASP provide a much better and easier way to send emails.
That’s where the PHPMailer Class comes in. It’s a free PHP class that makes sending emails with PHP easier and more powerful. You can download it here and here’s how to use it.
include("class.phpmailer.php");
// initiate the class
$mail=new PHPMailer();
// let’s use SMTP
$mail->IsSMTP();
$mail->Host="somehost.com";
$mail->Username="smtpusername";
$mail->Password="smtppassword";
// sender
$mail->From="sender@email.com";
$mail->FromName="Billy Joel";
// subject and message
$mail->Subject="email subject";
$mail->Body="email message";
// specify recipients
$mail->AddAddress("email@address.com");
$mail->AddAddress("email@address.net");
// send the email
$mail->Send();
?>
The power of PHPMailer is more than that. Through it you can add attachments to your email, specify an HTML body for your email, etc. Download it and check out the examples they provide.
Happy emailing and please, don’t spam. :)








June 25th, 2008 at 3:31 pm
[...] How to Send Email Using PHP [...]
February 4th, 2009 at 10:19 am
Thanks for the info