Sending php email via SMTP in Windows Server

Script to read web.config SMTP settings inside php and send email using phpmailer via SMTP in Windows Server.

if (smtp_mail( '<to>', '<subject>', '<message>', '<from>')) {
   echo 'Email sent!';
}
else {
   echo 'Error in sending email';
}

You have to replace all tags with their respective values.

	require_once 'phpmailer/class.smtp.php';
	require_once 'phpmailer/class.phpmailer.php';
	function smtp_mail( $to, $subject, $message, $from = '' ) {
		$config_from = '';
		$config_host = '';
		$config_pass = '';
		$config_user = '';
		$config_port = '';
		$sxe = simplexml_load_file("web.config");
		foreach($sxe->xpath("/configuration/system.net/mailSettings/smtp") as $item) {
			$config_from = $item['from'];
			$config_host = $item->network['host'];
			$config_pass = $item->network['password'];
			$config_user = $item->network['userName'];
			$config_port = $item->network['port'];
		}
		$config_from = !empty($from) ? $from : $config_from;
		$mailer = new PHPMailer();
		if (!empty($config_host) && !empty($config_user) && !empty($config_pass)) {
			$mailer->isSMTP();
			$mailer->SMTPAuth = true;
			$mailer->Host = $config_host;
			$mailer->Port = $config_port;
			$mailer->Username = $config_user;
			$mailer->Password = $config_pass;
		}
		$mailer->addAddress($to);
		$mailer->addReplyTo($config_from);
		$mailer->setFrom($config_from);
		$mailer->isHTML();
		$mailer->Subject = $subject;
		$mailer->msgHTML( $message );
		return $mailer->send();
	}

Leave a Reply

Your email address will not be published. Required fields are marked *

*