Sending Email with PHP on IIS: Difference between revisions

From Littledamien Wiki
Jump to navigation Jump to search
No edit summary
Line 1: Line 1:
==Enabling Email==
==Enabling Email==
*Make sure the SMTP port is open on the router.
*<strike>Make sure the SMTP port is open on the router.</strike> <<< not necessary for outbound traffic
*Make sure the SMTP service is running on the server.
*Make sure the SMTP service is running on the server.
==PHP Configuration==
==PHP Configuration==
The real hurtle I encountered was this error:
The real hurtle I encountered was this error:

Revision as of 01:07, 2 March 2012

Enabling Email

  • Make sure the SMTP port is open on the router. <<< not necessary for outbound traffic
  • Make sure the SMTP service is running on the server.

PHP Configuration

The real hurtle I encountered was this error:

warning: mail() [function.mail]: SMTP server response: 501 5.5.4 Invalid Address

The problem is that by default SMTP on Windows doesn't accept emails in the format From: John Doe <johndoe@domain.com> even though that format is RFC-compliant.

Something like this will fail on Windows (but work fine on *nix)

$headers = "From: {$sender_name} <{$sender_email}>\r\n";
mail($to, $subject, $body, $headers);

Whereas this will work:

$headers = "From: {$sender_email}\r\n";

Fix: edit php.ini:

sendmail_from = me@domain.com

PHP Code

mailer class

require_once(COMMON_CLASS_DIR."utils/mail_class.php");

sample code

try
{
	ob_start();
	include (APP_TEMPLATE_DIR."email/email_template.php");
	$body = ob_get_contents();
	ob_end_clean();

	$mail = new mail_class(
		$sender_name, 
		$sender_addr,
		$recipient_name,
		$recipient_addr,
		$subject,
		$body,
		false);

	$mail->send();
	unset($mail);
}
catch (Exception $ex) {
	throw new Exception("Mail failed: ".$ex->getMessage());
}