Sending emails

Using the mail() function

First, I should point you to the mail reference for some configuration options as well. They're available here: http://www.php.net/manual/en/ref.mail.php

Basic syntax is simple:

mail("toAddress","Subject","Message"[, "headerInfo"[, "options"]]);

A simple example

	mail("phpclass@linux-classes.com","This is a test","Hello phpclass!");

More advanced

I usually think it's better to set up some standard variable to pass to the mail function. Example:

	$to = "phpclass@linux-classes.com";
	$subject = "This is a test";
	$message = "Hello phpclass!";
	$headers = "";
	mail($to, $subject, $message, $headers);

Why??? Because if I want to add header information, I can simply append the $headers variable.

For example, I can force the "From" header by doing the following:

	$headers.="From: myEmail@my.com\r\n";

Notice the "\r\n", this is needed for the mail server to properly parse the header information

I can also set the other headers as well. Example:

	$headers.="Reply-To: myOtherEmail@my.com\r\n";
	$headers.="Cc: copyAddress@my.com\r\n";
	$headers.="Bcc: nastyCopy@my.com\r\n";

Want to send out an html version of an email? Set the content type in the header. Example:

	$headers  = "MIME-Version: 1.0\r\n"; //Use Mime 1.0
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; //Sets html content type and char set as iso-8859-1 (European)

Putting it all together

If we put all of the above together, we get this...

	//Set to and subject vars
	$to = "phpclass@linux-classes.com";
	$subject = "This is a test";
	//Create html message
	$message = "<html><head><style type='text/css'>* {font-family:arial;}</style></html><body>";
	$message.="<p>This is an html message</p>";
	$message.="<p><a href='http://link.com/to/may/page'>This is a link</a></p>";
	$message.="</body></html>";
	$headers = "";
	$headers.="From: myEmail@my.com\r\n";
	$headers.="Reply-To: myOtherEmail@my.com\r\n";
	$headers.="Cc: copyAddress@my.com\r\n";
	$headers.="Bcc: nastyCopy@my.com\r\n";
	$headers  = "MIME-Version: 1.0\r\n"; //Use Mime 1.0
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; //Sets html content type and char set as iso-8859-1 (European)
	mail($to, $subject, $message, $headers);

This will send a nicely formatted html email to phpclass@linux-classes.com.