Send an email via the SMTP connection protocol

The connection via the protocol adapter is made just-in-time to allow a
developer to add a custom adapter if required before mail is sent.

@return void
@todo Rename this to sendMail, it's a public method...
340258
public function _sendMail()
    {
        // If sending multiple messages per session use existing adapter
        if (!($this->_connection instanceof Zend_Mail_Protocol_Smtp)) {
            // Check if authentication is required and determine required class
            $connectionClass = 'Zend_Mail_Protocol_Smtp';
            if ($this->_auth) {
                $connectionClass .= '_Auth_' . ucwords($this->_auth);
            }
            if (!class_exists($connectionClass)) {
                // require_once 'Zend/Loader.php';
                Zend_Loader::loadClass($connectionClass);
            }
            $this->setConnection(new $connectionClass($this->_host, $this->_port, $this->_config));
            $this->_connection->connect();
            $this->_connection->helo($this->_name);
        } else {
            // Reset connection to ensure reliable transaction
            $this->_connection->rset();
        }

        // Set sender email address
        $this->_connection->mail($this->_mail->getReturnPath());

        // Set recipient forward paths
        foreach ($this->_mail->getRecipients() as $recipient) {
            $this->_connection->rcpt($recipient);
        }

        // Issue DATA command to client
        $this->_connection->data($this->header . Zend_Mime::LINEEND . $this->body);
    }
885686
def connect
      begin
        smtp = Net::SMTP.new(self.host_name || self.ip_address)
        smtp.start(@config[:smtp_helo_name] || 'localhost')
        smtp.mailfrom @config[:smtp_mail_from] || 'postmaster@localhost'
        smtp.rcptto self.to_s
        #p [:connect]
        smtp.finish
        true
      rescue Net::SMTPUnknownError => e
        set_error(:address_unknown, e.to_s)
      rescue Net::SMTPFatalError => e
        set_error(:address_unknown, e.to_s)
      rescue SocketError => e
        set_error(:address_unknown, e.to_s)
      ensure
        if smtp && smtp.started?
          smtp.finish
        end
        !!@error
      end
    end
165569
public function send()
    {
    	if(!$this->getTemplate()->getIsActive())
    	{
    		return $this;
    	}
    	
        if(!$this->isRendered())
	    {
	      $this->render();
	    }
	    
    	$eventParams = array(
    			'mailer'    => $this->getMailer(),
    			'message'   => $this->getMessage(),
    			'template'  => $this->getTemplate()
    	);

    	$this->getMailer()->send($this->getMessage());
    	$this->sentMailer->createSentMail($this->getTemplate());
    
    	return $this;
    }
701979
protected function _send()
	{
		// Build the message
		$message = $this->build_message();

		// Open a connection
		$return_path = ($this->config['return_path'] !== false) ? $this->config['return_path'] : $this->config['from']['email'];
		$handle = @popen($this->config['sendmail_path'] . " -oi -f ".$return_path." -t", 'w');

		// No connection?
		if(! is_resource($handle))
		{
			throw new \SendmailConnectionException('Could not open a sendmail connection at: '.$this->config['sendmail_path']);
		}

		// Send the headers
		fputs($handle, $message['header']);

		// Send the body
		fputs($handle, $message['body']);

		if(pclose($handle) === -1)
		{
			throw new \SendmailFailedException('Failed sending email through sendmail.');
		}

		return true;
	}
1269207
public function send($email = 0)
    {

        if ($email instanceof Email) {
            $this->addEmailToOutbox($email);
        }

        $sent_emails = 0;

        foreach ($this->emails as &$email) {
            
            //all email goes to DEBUG_EMAIL if specified
            if (defined("DEBUG_EMAIL")) {
                $email->debug_info = "\n\nDEBUG MODE: Should be sent to: " . $email->to . " when not in debug mode!";
                $email->debug_info .= "\nDEBUG MODE: Should be sent from: " . $email->from . " when not in debug mode!";

                $email->to = \DEBUG_EMAIL;
                $email->from = \DEBUG_EMAIL;

                if (!empty($email->cc)) {
                    $email->debug_info .= "\nDEBUG MODE: Should be be CCed to: "
                        . implode(", ", $email->cc) . " when not in debug mode!";
                    $email->cc = Array();
                }

                if (!empty($email->bcc)) {
                    $email->debug_info .= "\nDEBUG MODE: Should be be BCCed to: "
                        . implode(", ", $email->bcc) . " when not in debug mode!";
                    $email->bcc = Array();
                }

                $email->body .= $email->debug_info;
                if (!empty($email->body_HTML)) {
                    $email->body_HTML .= nl2br($email->debug_info);
                }
            }
            $email->to = $email->to ? $email->to : null;
            $email->constructMultipartMessage();
            
            //sanitize sender params
            if(preg_match("~<(.*?)>~", $email->from, $match)){
                $sender = $match[1];
            } else {
                $sender = $email->from;
            }
      
            $sender = filter_var($sender, FILTER_SANITIZE_EMAIL);
            $params = sprintf('-f%s', escapeshellcmd($sender));
    
            if (mail($email->to, $email->subject, $email->body, $email->_header_text, $params)) {

                $email->sent = 1;
                $sent_emails++;

                $this->logEmail($email, true);
            } else {
                $this->logEmail($email, false);
            }
        }

        $emails_cnt = count($this->emails);

        $this->emails = Array();

        if ($sent_emails == $emails_cnt) {
            return true;
        } else {
            return false;
        }
    }
740825
public function send()
    {
        $this->validate();

        $settings = array();
        $settings['helo_hostname'] = $this->_helo_hostname;
        if ($this->_auth) {
            $settings['username'] = $this->_user;
            $settings['password'] = $this->_pass;
        }
        $settings['secure'] = $this->_secure;

        try {
            if (!is_a($this->_SMTP, 'SMTP')) {
                $this->_SMTP = new SMTP($this->_host, $this->_port, $settings);
            }

            // Encode recipient names (but not any numeric array indexes)
            $recipients = array();
            foreach ($this->_recipients as $name => $email) {
                // Support Bcc header
                if (isset($this->_header_fields['Bcc']) && $this->_header_fields['Bcc'] == $email) {
                    continue;
                }

                // if the key is not numeric, qEncode the key.
                $name = General::intval($name) > -1 ? General::intval($name) : EmailHelper::qEncode($name);
                $recipients[$name] = $email;
            }

            // Combine keys and values into a recipient list (name <email>, name <email>).
            $recipient_list = EmailHelper::arrayToList($recipients);

            // Encode the subject
            $subject = EmailHelper::qEncode((string)$this->_subject);

            // Build the 'From' header field body
            $from = empty($this->_sender_name)
                    ? $this->_sender_email_address
                    : EmailHelper::qEncode($this->_sender_name) . ' <' . $this->_sender_email_address . '>';

            // Build the 'Reply-To' header field body
            if (!empty($this->_reply_to_email_address)) {
                $reply_to = empty($this->_reply_to_name)
                            ? $this->_reply_to_email_address
                            : EmailHelper::qEncode($this->_reply_to_name) . ' <'.$this->_reply_to_email_address.'>';
            }

            if (!empty($reply_to)) {
                $this->_header_fields = array_merge(
                    $this->_header_fields,
                    array(
                        'Reply-To' => $reply_to,
                    )
                );
            }

            // Build the body text using attachments, html-text and plain-text.
            $this->prepareMessageBody();

            // Build the header fields
            $this->_header_fields = array_merge(
                $this->_header_fields,
                array(
                    'Message-ID'   => sprintf('<%s@%s>', md5(uniqid()), HTTP_HOST),
                    'Date'         => date('r'),
                    'From'         => $from,
                    'Subject'      => $subject,
                    'To'           => $recipient_list,
                    'MIME-Version' => '1.0'
                )
            );

            // Set header fields and fold header field bodies
            foreach ($this->_header_fields as $name => $body) {
                $this->_SMTP->setHeader($name, EmailHelper::fold($body));
            }

            // Send the email command. If the envelope from variable is set, use that for the MAIL command. This improves bounce handling.
            $this->_SMTP->sendMail(is_null($this->_envelope_from)?$this->_sender_email_address:$this->_envelope_from, $this->_recipients, $this->_body);

            if ($this->_keepalive === false) {
                $this->closeConnection();
            }

            $this->reset();
        } catch (SMTPException $e) {
            throw new EmailGatewayException($e->getMessage());
        }

        return true;
    }
350256
public function send()
    {
        $mimeMessage = $this->createMimeMessage();
        $this->message = $mimeMessage;
        $this->preparingSend();
        imap_mail(
            $this->properties->to,
            $this->properties->subject,
            $this->properties->message,
            $this->properties->additional_headers,
            $this->properties->cc,
            $this->properties->bcc,
            $this->properties->rpath
        );
    }
1018341
def _message_send(self, connection):
    
    sender = current_app.config["MAIL_SENDER"]
    if not self.extra_headers:
        self.extra_headers = {}
    self.extra_headers["Sender"] = sender
    connection.send(self, sender)
1367645
public function Send()
    {
        try {
            if (!$this->PreSend()) return false;
            return $this->PostSend();
        } catch (phpmailerException $e) {
            $this->SetError($e->getMessage());
            if ($this->exceptions) {
                throw $e;
            }
            return false;
        }
    }
710807
public function sendMail(Mail $mail) {
		$sender = $mail->getSender();
		if (!$sender instanceof MailAddress) {
			throw new SmtpException('no sender found on mail');
		}
		$this->mail($sender->getEmail());
		
		foreach ($mail->getRecipients() as $address) {
			$address instanceof MailAddress;
			// @todo: catch errors
			$this->recipient($address->getEmail());
		}
		
		$this->data($mail->getData());
	}
610527
protected function _tls()
    {
        if ($this->_secure == 'tls') {
            $this->_send('STARTTLS');
            $this->_expect(220, 180);
            if (!stream_socket_enable_crypto($this->_connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                throw new SMTPException(__('Unable to connect via TLS'));
            }
            $this->_ehlo();
        }
    }
40585
public function connect()
	{
		if ($this->connection)
		{
			return;
		}

		// Make sure the postgresql extension for PHP is installed and enabled.
		if (!static::isSupported())
		{
			throw new UnsupportedAdapterException('PHP extension pg_connect is not available.');
		}

		/*
		 * The pg_connect() function takes the port as separate argument. Therefore, we
		 * have to extract it from the host string (if povided).
		 */

		// Check for empty port
		if (!$this->options['port'])
		{
			// Port is empty or not set via options, check for port annotation (:) in the host string
			$tmp = substr(strstr($this->options['host'], ':'), 1);

			if (!empty($tmp))
			{
				// Get the port number
				if (is_numeric($tmp))
				{
					$this->options['port'] = $tmp;
				}

				// Extract the host name
				$this->options['host'] = substr($this->options['host'], 0, \strlen($this->options['host']) - (\strlen($tmp) + 1));

				// This will take care of the following notation: ":5432"
				if ($this->options['host'] === '')
				{
					$this->options['host'] = 'localhost';
				}
			}

			// No port annotation (:) found, setting port to default PostgreSQL port 5432
			else
			{
				$this->options['port'] = '5432';
			}
		}

		// Build the DSN for the connection.
		$dsn = "host={$this->options['host']} port={$this->options['port']} dbname={$this->options['database']} " .
			"user={$this->options['user']} password={$this->options['password']}";

		// Attempt to connect to the server.
		if (!($this->connection = @pg_connect($dsn)))
		{
			$this->log(Log\LogLevel::ERROR, 'Error connecting to PGSQL database.');

			throw new ConnectionFailureException('Error connecting to PGSQL database.');
		}

		pg_set_error_verbosity($this->connection, PGSQL_ERRORS_DEFAULT);
		pg_query($this->connection, 'SET standard_conforming_strings=off');
		pg_query($this->connection, 'SET escape_string_warning=off');
		pg_query($this->connection, 'SET bytea_output=escape');
	}
635986
protected function _connect()
    {
        if (is_resource($this->_connection)) {
            // connection already exists
            return;
        }

        if (!extension_loaded('oci8')) {
            /**
             * @see Zend_Db_Adapter_Oracle_Exception
             */
            // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
            throw new Zend_Db_Adapter_Oracle_Exception('The OCI8 extension is required for this adapter but the extension is not loaded');
        }

        $this->_setExecuteMode(OCI_COMMIT_ON_SUCCESS);

        $connectionFuncName = ($this->_config['persistent'] == true) ? 'oci_pconnect' : 'oci_connect';

        $this->_connection = @$connectionFuncName(
                $this->_config['username'],
                $this->_config['password'],
                $this->_config['dbname'],
                $this->_config['charset']);

        // check the connection
        if (!$this->_connection) {
            /**
             * @see Zend_Db_Adapter_Oracle_Exception
             */
            // require_once 'Zend/Db/Adapter/Oracle/Exception.php';
            throw new Zend_Db_Adapter_Oracle_Exception(oci_error());
        }
    }
299092
public function send()
    {
        if (!$this->mailSender) {
            throw new \Parable\Mail\Exception('No mail sender implementation set.');
        }

        // Check the basics
        if (count($this->addresses['to']) === 0) {
            throw new \Parable\Mail\Exception('No to addresses provided.');
        }
        if (empty($this->subject)) {
            throw new \Parable\Mail\Exception('No subject provided.');
        }
        if (empty($this->body)) {
            throw new \Parable\Mail\Exception('No body provided.');
        }

        // Handle the to, cc and bcc addresses
        $to  = $this->getAddressesForType('to');
        $cc  = $this->getAddressesForType('cc');
        $bcc = $this->getAddressesForType('bcc');

        if (!empty($cc)) {
            $this->addHeader("Cc: {$cc}");
        }
        if (!empty($bcc)) {
            $this->addHeader("Bcc: {$bcc}");
        }

        // Handle from
        $from = $this->getAddressesForType('from');
        $this->addHeader("From: {$from}");

        $headers = array_merge($this->requiredHeaders, $this->headers);
        $headers = implode("\r\n", $headers);

        return $this->getMailSender()->send($to, $this->subject, $this->body, $headers);
    }
30011
public function _sendMail()
    {
        if ($this->parameters === null) {
            set_error_handler(array($this, '_handleMailErrors'));
            $result = mail(
                $this->recipients,
                $this->_mail->getSubject(),
                $this->body,
                $this->header);
            restore_error_handler();
        } else {
            if(!is_string($this->parameters)) {
                /**
                 * @see Zend_Mail_Transport_Exception
                 *
                 * Exception is thrown here because
                 * $parameters is a public property
                 */
                // require_once 'Zend/Mail/Transport/Exception.php';
                throw new Zend_Mail_Transport_Exception(
                    'Parameters were set but are not a string'
                );
            }

            set_error_handler(array($this, '_handleMailErrors'));
            $result = mail(
                $this->recipients,
                $this->_mail->getSubject(),
                $this->body,
                $this->header,
                $this->parameters);
            restore_error_handler();
        }

        if ($this->_errstr !== null || !$result) {
            /**
             * @see Zend_Mail_Transport_Exception
             */
            // require_once 'Zend/Mail/Transport/Exception.php';
            throw new Zend_Mail_Transport_Exception('Unable to send mail. ' . $this->_errstr);
        }
    }
526779
function SmtpConnect() {
    if($this->smtp == NULL) { $this->smtp = new SMTP(); }

    //Added for Gmail support CER
    $this->smtp->Protocol = $this->Protocol;

    $this->smtp->do_debug = $this->SMTPDebug;
    $hosts = explode(";", $this->Host);
    $index = 0;
    $connection = ($this->smtp->Connected());

    // Retry while there is no connection
    while($index < count($hosts) && $connection == false)
    {
      if(strstr($hosts[$index], ":"))
      list($host, $port) = explode(":", $hosts[$index]);
      else
      {
        $host = $hosts[$index];
        $port = $this->Port;
      }

      if($this->smtp->Connect($host, $port, $this->Timeout))
      {
        if ($this->Helo != '')
        $this->smtp->Hello($this->Helo);
        else
        $this->smtp->Hello($this->ServerHostname());

        if($this->SMTPAuth)
        {
          if(!$this->smtp->Authenticate($this->Username,
          $this->Password))
          {
            $this->SetError($this->Lang("authenticate"));
            $this->smtp->Reset();
            $connection = false;
          }
        }
        $connection = true;
      }
      $index++;
    }
    if(!$connection)
    $this->SetError($this->Lang("connect_host"));

    return $connection;
  }
473677
public function send_headers()
	{
		if ( ! headers_sent())
		{
			// Send the protocol/status line first, FCGI servers need different status header
			if ( ! empty($_SERVER['FCGI_SERVER_VERSION']))
			{
				header('Status: '.$this->status.' '.static::$statuses[$this->status]);
			}
			else
			{
				$protocol = \Input::server('SERVER_PROTOCOL') ? \Input::server('SERVER_PROTOCOL') : 'HTTP/1.1';
				header($protocol.' '.$this->status.' '.static::$statuses[$this->status]);
			}

			foreach ($this->headers as $name => $value)
			{
				// Parse non-replace headers
				if (is_int($name) and is_array($value))
				{
					 isset($value[0]) and $name = $value[0];
					 isset($value[1]) and $value = $value[1];
				}

				// Create the header
				is_string($name) and $value = "{$name}: {$value}";

				// Send it
				header($value, true);
			}
			return true;
		}
		return false;
	}