PHP SwiftMailer类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP SwiftMailer类相关的知识,希望对你有一定的参考价值。

<?php

/**
 * Generic class for sending emails
 * @author manilodisan
 * 
 */

class Email {

	public $swiftPath;

	//	Email type
	public $type = 'text/html';

	//	Mailer instance
	private $mailer;

	//	TRUE/FALSE to use SMTP authentication or not
	private $_bUseSMTP = FALSE;

	//	TRUE/FALSE to use Sendmail
	private $_bUseSendmail;

	//	The sendmail command. Default: /usr/sbin/sendmail -bs
	private $_sendmailCommand;

	//	Keeping it to TRUE, will throw exceptions if something bad
	//	happens. On FALSE, it will try to ignore errors and continue
	//	it's task
	public $bThrowExceptions = TRUE;

	//	Alternative body message for text only recipients
	public $sAltMessage = "To view the message, please use a HTML compatible email viewer!";

	//	Holds the recipients of the email
	private $_aRecipients = array ();

	//	Holds the attachments of the email, if any
	private $_aAttachments = array ();

	//	Tokens, if any
	private $_aTokens = array ();

	//	Sender's name
	private $_sFromName;

	//	Sender's email address
	private $_sFromEmail;

	//	Default Smtp host
	private $_sSmtpHost;

	//	Default Smtp username
	private $_sSmtpUser;

	//	Default Smtp password
	private $_sSmtpPassword;

	//	Default Smtp port
	private $_sSmtpPort;

	//	Smtp authentication type: ssl, tls
	private $_sSmtpSecure;

	private $_lastError;

	public function __construct () {
		//	set a default path
		$this->swiftPath = realpath ( dirname ( __FILE__ ) ) . '/libraries/swiftmailer/';
		if ( ! file_exists ( $this->swiftPath . 'swift_required.php' ) ) {
			throw new CException ( "SwiftMailer library file not found" );
		}
		
		spl_autoload_unregister ( array ( 
			
			'YiiBase', 
			'autoload' 
		) );
		
		require_once ( $this->swiftPath . 'swift_required.php' );

		spl_autoload_register ( array ( 
			
			'YiiBase', 
			'autoload' 
		) );
		
	}

	/**
	 * Used to send the email. Should be called last
	 * @param string $subject The email subject
	 * @param string $message The email body
	 * @return boolean TRUE/FALSE
	 */
	public function send ( $subject, $message ) {
		ini_set ("max_execution_time",10);
		if ( ! count ( $this->_aRecipients ) ) {
			if ( $this->bThrowExceptions ) {
				throw new CException ( "No recipients found. Email failed" );
			}
			return FALSE;
		}
		
		$sent = FALSE;
		
		if ( $this->_bUseSMTP ) {
			$transport = Swift_SmtpTransport::newInstance ( $this->_sSmtpHost, $this->_sSmtpPort, $this->_sSmtpSecure )->setUsername ( $this->_sSmtpUser )->setPassword ( $this->_sSmtpPassword );
		}
		elseif ( $this->_bUseSendmail ) {
			$transport = Swift_SendmailTransport::newInstance ( $this->_sendmailCommand );
		}
		else {
			//	mail function is used here
			$transport = Swift_MailTransport::newInstance ();
		}
		
		$this->mailer = Swift_Mailer::newInstance ( $transport );

		$message = Swift_Message::newInstance ()->setFrom ( array ( 
			
			$this->_sFromEmail, 
			$this->_sFromName 
		) )->setSubject ( $subject );
		
		$this->__processTokens ();

		$to = array ();
		foreach ( $this->_aRecipients as $aRecipient ) {
			if ( $aRecipient [ 'name' ] ) {
				$to [ $aRecipient [ 'email' ] ] = $aRecipient [ 'name' ];
			}
			else {
				array_push ( $to, $aRecipient [ 'email' ] );
			}
		}

		$message->setTo ( $to );

		foreach ( $this->_aAttachments as $aAttachment ) {
			switch ( $aAttachment [ 'type' ] ) {
				case 'inline' :
					$message->embed ( Swift_Attachment::fromPath ( $aAttachment [ "path" ] ) );
					$this->type = 'text/html';
					break;
				default :
				case 'attachment' :
					$message->attach ( Swift_Attachment::fromPath ( $aAttachment [ "path" ] ) );
					break;
			}
		
		}

		$message->setBody ( $message, $this->type );

		if ( $this->mailer->batchSend ( $message ) ) {
			$this->_aRecipients = array ();
			return TRUE;
		}
		return FALSE;
	}

	private function __processTokens () {
		if ( count ( $this->_aTokens ) ) {
			$replacements = array ();
			foreach ( $this->_aRecipients as $aRecipient ) {
					$replacements [ $aRecipient [ 'email' ] ] = $this->_aTokens;
			}
	
			$decorator = new Swift_Plugins_DecoratorPlugin ( $replacements );
			$this->mailer->registerPlugin ( $decorator );
		}
	}

	public function getRecipients () {
		return $this->_aRecipients;
	}

	/**
	 * Adds a recipient/receiver
	 * @param string $name The name of our recipient: e.g John Doe
	 * If the recipient name is not provided, the email is used instead
	 * @param string $email The email recipient
	 * @param array $search Should we look for things to replace? Maybe some tokens, e.g. {name}, {username}
	 * @param array $replace Replace values for the above searches
	 * @return void
	 */
	public function addRecipient ( $email, $name = FALSE ) {
		if ( Validator::isValidEmail ( $email ) ) {
			$this->_aRecipients [] = array ( 
				
				'email' => $email, 
				'name' => ( $name ) ? $name : '' 
			);
		}
		else {
			if ( $this->bThrowExceptions ) {
				throw new CException ( "Email $email is not a valid recipient" );
			}
		}
	}

	/**
	 * Adds an attachment to our email
	 * @param string $path Full path to our attachment file
	 * @param string $type Type of attachment (attachment/inline)
	 * @return void
	 */
	public function addAttachment ( $path, $type = 'attachment' ) {
		if ( @file_exists ( $path ) ) {
			$this->_aAttachments [] = array ( 
				
				'path' => $path, 
				'type' => $type 
			);
		}
		else {
			if ( $this->bThrowExceptions ) {
				throw new CException ( "Attachment at $path does not exist. Check your path" );
			}
		}
	}

	public function addTokens ( $search = array (), $replace = array () ) {
		$this->_aTokens = array_merge ( $this->_aTokens, array_combine ( $search, $replace ) );
	}

	/**
	 * Sets the 'reply to' headers. The receiver of replies should be defined here
	 * @param string $email The reply-to email address
	 * @param string $name The reply-to name: e.g John Doe
	 * If the reply-to name is not provided, the reply-to email is used instead
	 * @return void
	 */
	public function setReplyTo ( $email, $name = '' ) {
		if ( Validator::isValidEmail ( $email ) ) {
			$this->_sReplyToEmail = $email;
			$this->_sReplyToName = ( $name != '' ) ? $name : $email;
		}
		else {
			if ( $this->bThrowExceptions ) {
				throw new CException ( "Email $email is not a valid reply-to email" );
			}
		}
	}

	/**
	 * Sets the 'from' headers. The sender should be set here
	 * @param string $email The sender's email address
	 * @param string $name The sender's name: e.g John Doe
	 * @return void
	 */
	public function setFrom ( $email, $name = '' ) {
		if ( Validator::isValidEmail ( $email ) ) {
			$this->_sFromEmail = $email;
			$this->_sFromName = ( $name != '' ) ? $name : $email;
		}
		else {
			if ( $this->bThrowExceptions ) {
				throw new CException ( "Email $email is not a valid From email" );
			}
		}
	}

	/**
	 * Returns the number of successfully sent messages
	 * @return int
	 */
	public function getSentCount () {
		return ( int ) $this->_iSent;
	}

	/**
	 * Returns the number of failed messages
	 * @return int
	 */
	public function getFailedCount () {
		return ( int ) $this->_iFailed;
	}

	/**
	 * Sets the SMTP settings. If this is not set, the mailer will use sendmail or @mail
	 * @param string $host SMTP host
	 * @param string $user SMTP username
	 * @param string $pass SMTP password
	 * @param integer $port SMTP port, default 25
	 * @return void
	 */
	public function setSmtp ( $host, $user, $pass, $port = 25, $authType = '' ) {
		if ( $authType != '' ) {
			$this->_sSmtpSecure = $authType;
		}
		$this->_bUseSMTP = TRUE;
		$this->_sSmtpHost = $host;
		$this->_sSmtpPort = $port;
		$this->_sSmtpUser = $user;
		$this->_sSmtpPassword = $pass;
	}

	/**
	 * Sets the Sendmail settings.
	 * @param string $command Command to use for setting up Sendmail. Ex: /usr/sbin/sendmail -bs
	 * @return void
	 */
	public function setSendmail ( $command = false ) {
		$this->_bUseSendmail = TRUE;
		if ( FALSE !== $command ) {
			$this->_sendmailPath = $command;
		}
	}

}

以上是关于PHP SwiftMailer类的主要内容,如果未能解决你的问题,请参考以下文章

使用 SwiftMailer 的 PHP 附件

PHP - 使用 STARTTLS 和自签名证书的 Swiftmailer

php swiftmailer的例子

使用 Swiftmailer 的 PHP 驱动的 HTML 联系表单有多安全?

使用 php、gmail 和 swiftmailer 发送电子邮件会导致与 SSL 相关的错误

无法让sendmail与Windows上的Swiftmailer Bundle一起使用