PHP Code

A handy function to make PHPMailer a little more efficient

It is very easy to send an email with PHP. However, many people prefer to user PHP mailer, because it's more reliable and has great features. You can send through an SMTP server. You can include attachments, and log errors. However, rather than one simple line of code to the PHP mail() function, it requires like 10 lines of code or more to send one email.

Well, if you send emails from various places within your application, you can create a function that can be referenced in one line of code, just like the mail() function. However, the function contains the defaults and the code to actually send the email through PHPmailer. Here's the function:

function sendMail($to, $subject, $body, $from="", $fromName="Default From Name") {
	$mail = new PHPMailer();
	$mail->SetLanguage("en", $lang_path = SITE_DOC_ROOT . "/classes/phpmailer/language/") ;
	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->Host = "localhost"; // SMTP server
	$Mail->Port = 25;
	$mail->SMTPAuth = true;
	$mail->Username = "username";
	$mail->Password = "password";
	$mail->From = $from;
	$mail->FromName = $fromName;
	$mail->Subject = stripslashes($subject);
	$mail->Body = stripslashes($body);
	//$mail->WordWrap = 120;
	return $mail->Send();

This will return true of false, just like the mail() function!



  1. Where do I put this code in my contact form? And how do I use it?

  2. You would put this code is a common, included library page where you keep all your common functions. You would use it by calling it like any other function

Leave a Reply

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

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image