jrobinsonc
4/15/2013 - 1:34 PM

Send emails with PHPMailer.

Send emails with PHPMailer.

<?php

/**
 * PHPMailer
 * Download: https://github.com/Synchro/PHPMailer/archive/master.zip
 */
define('PHPMailer_path', dirname(__FILE__) . '/PHPMailer');


/**
 * send_mail
 * 
 * @param string|array $to
 * @param string $subject
 * @param string|array $body
 * @param array $attachments
 * @return mixed Devuelve TRUE si todo paso bien o un String con el error si algo fallo.
 */
function send_mail($to, $subject, $body, $attachments = array(), $config = array())
{
    require_once PHPMailer_path . '/class.phpmailer.php';
	
    $mail = new PHPMailer();
    //$mail->SMTPDebug  = 2;
    
	if (isset($config['smtp']) && $config['smtp'] === TRUE) 
	{
		$mail->IsSMTP();
		
		$mail->Host = $config['smtp_host'];
		
		$mail->SMTPAuth = isset($config['smtp_auth'])? $config['smtp_auth'] : FALSE;
		$mail->SMTPSecure = isset($config['smtp_secure'])? $config['smtp_secure'] : '';
		
		$mail->Username = $config['smtp_user'];
		$mail->Password = $config['smtp_pass'];
		
		if (isset($config['smtp_port']))
			$mail->Port = $config['smtp_port'];
	}

	if (isset($config['from']))
	{
		if (is_string($config['from']))
			$config['from'] = array($config['from']);
		
		if (!isset($config['from'][1]))
			$config['from'][1] = '';
		
		$mail->SetFrom($config['from'][0], $config['from'][1]);
		$mail->AddReplyTo($config['from'][0], $config['from'][1]);
	}
    
	$mail->Subject = $subject;
    
	if (is_string($body))
	{
		$mail->Body = $body;
	}
	else
	{
		if (isset($body['html'])) 
		{
			$mail->IsHTML(TRUE);
			$mail->Body = $body['html'];
		}

		if (isset($body['text']))
		{
			$mail->AltBody = $body['text'];
		}
	}
			
    if (count($attachments) > 0)
    {
        foreach ($attachments as $attachment)
        {
            if (!is_file($attachment)) continue;
            
            $mail->AddAttachment($attachment);
        }
    }
    
    if (is_string($to))
		$to = array($to);
		
	if (!isset($to[1]))	
		$to[1] = '';
	
	$mail->AddAddress($to[0], $to[1]);
	
	//---------------------------------------------------
	$result = $mail->Send()? TRUE : $mail->ErrorInfo;
		
    return $result;
}