Send email

@access public
977654
public function send() {
		if (!$this->validate($errors)) {
			throw new \Exception('Cannot send email, Mail not validated. Errored fields: ' . implode(', ', $errors));
		}

		if (Config::$archive_mailbox !== null) {
			$this->add_bcc(Config::$archive_mailbox);
		}

		$template = new \Skeleton\Template\Template();
		if ($this->translation !== null) {
			$template->set_translation($this->translation);
		}

		if (count($this->template_directories) == 0) {
			$this->add_template_directory(Config::$email_directory . '/template/');
		}

		foreach ($this->template_directories as $template_directory) {
			$template->add_template_directory($template_directory['directory'], $template_directory['namespace']);
		}

		foreach ($this->assigns as $key => $value) {
			$template->assign($key, $value);
		}

		$transport = \Swift_MailTransport::newInstance();
		$mailer = \Swift_Mailer::newInstance($transport);
		$message = \Swift_Message::newInstance()
			->setBody($template->render( $this->type . '/html.twig'), 'text/html')
			->addPart($template->render( $this->type . '/text.twig' ), 'text/plain')
			->setSubject(trim($template->render( $this->type . '/subject.twig' )))
		;

		// Add header
		if (isset(\Skeleton\Email\Config::$email_type_header) AND \Skeleton\Email\Config::$email_type_header !== null) {
			$headers = $message->getHeaders();
			$headers->addTextHeader(\Skeleton\Email\Config::$email_type_header, $this->type);
		}

		// Set sender
		if (isset($this->sender['name'])) {
			$message->setFrom([$this->sender['email'] => $this->sender['name']]);
		} else {
			$message->setFrom($this->sender['email']);
		}

		// Set reply to
		foreach ($this->reply_to as $reply_to) {
			if (isset($reply_to['name'])) {
				$message->setReplyTo([ $reply_to['email'] => $reply_to['name'] ]);
			} else {
				$message->setReplyTo($reply_to['email']);
			}
		}

		$this->add_html_images($message);
		$this->attach_files($message);

		// Remove duplicate recipients, in order of importance
		$types = ['bcc', 'cc', 'to'];
		foreach ($types as $type) {
			array_shift($types);

			if (count($types) === 0) {
				continue;
			}

			if (isset($this->recipients[$type])) {
				foreach ($this->recipients[$type] as $key => $recipient) {
					if ($this->addressee_exists($recipient['email'], $types)) {
						unset($this->recipients[$type][$key]);
					}
				}
			}
		}

		// Add recipients
		foreach ($this->recipients as $type => $recipients) {
			$addresses = [];

			foreach ($recipients as $recipient) {
				if (!empty(\Skeleton\Email\Config::$redirect_all_mailbox)) {
					$recipient['email'] = \Skeleton\Email\Config::$redirect_all_mailbox;
				}

				if (!\Swift_Validate::email($recipient['email'])) {
					if (Config::$strict_address_validation !== false) {
						throw new Exception\Validation('Invalid e-mail address: ' . $recipient['email']);
					} else {
						continue;
					}
				}

				if ($recipient['name'] != '') {
					$addresses[$recipient['email']] = $recipient['name'];
				} else {
					$addresses[] = $recipient['email'];
				}
			}

			$set_to = 'set' . ucfirst($type);

			try {
				call_user_func([$message, $set_to], $addresses);
			} catch (\Swift_RfcComplianceException $e) {
				if (Config::$strict_address_validation !== false) {
					throw new Exception\Validation($e->getMessage());
				}
			}
		}

		// If we have no recipients in the message, and strict validation is
		// disabled, and we do have recipients locally, fail silently. This means
		// all recipients set by the user were invalid.
		if (
			(count($message->getTo()) < 1 and count($message->getCc()) < 1 and count($message->getBcc()) < 1) and
			(isset($this->recipients) and count($this->recipients) > 0) and
			Config::$strict_address_validation === false
		) {
			return;
		}

		$mailer->send($message);
		unset($template);
	}
477428
public function send($bGraceful = false)
    {
        $aEmail = $this->toArray();
        $aData  = [
            'type'     => $aEmail['sType'],
            'to_id'    => null,
            'to_email' => null,
            'data'     => (object) $aEmail['aData'],
        ];

        if (!empty($aEmail['sSubject']) & empty($aData['data']->email_subject)) {
            $aData['data']->email_subject = $aEmail['sSubject'];
        }

        if (!empty($aEmail['sFromName']) & empty($aData['data']->email_from_name)) {
            $aData['data']->email_from_name = $aEmail['sFromName'];
        }

        if (!empty($aEmail['sFromEmail']) & empty($aData['data']->email_from_email)) {
            $aData['data']->email_from_email = $aEmail['sFromEmail'];
        }

        if (!empty($aEmail['aCc']) & empty($aData['data']->cc)) {
            $aData['data']->cc = $aEmail['aCc'];
        }

        if (!empty($aEmail['aBcc']) & empty($aData['data']->bcc)) {
            $aData['data']->bcc = $aEmail['aBcc'];
        }

        $oEmailer = Factory::service('Emailer', 'nails/module-email');

        foreach ($aEmail['aTo'] as $mUserIdOrEmail) {

            if (is_numeric($mUserIdOrEmail)) {
                $aData['to_id'] = $mUserIdOrEmail;
            } elseif (valid_email($mUserIdOrEmail)) {
                $aData['to_email'] = $mUserIdOrEmail;
            }

            $this->bLastEmailDidSend = $oEmailer->send($aData, $bGraceful);
        }

        return $this;
    }
361239
public function sendEmail()
    {
        $mandrill = new Mandrill(Yii::$app->params['mandrill']['key']);
        $message = [
            'html' => $this->html,
            'text' => $this->text,
            'subject' => $this->subject,
            'from_email' => $this->from_email,
            'from_name' => $this->from_name,
            'track_opens' => true,
            'track_clicks' => true,
            'auto_text' => true,
            'to' => [['email' => $this->to_email, 'name' => $this->to_name]],
            'bcc_address' => 'mihai.petrescu@gmail.com',
        ];
        $result = $mandrill->messages->send($message);
        if ($result[0]['status'] == 'sent') {
            $this->status = 'sent';
        } else {
            $this->tries++;
        }
        $this->save();
    }
1282764
public function send()
    {
        $this->_mailer->addAddress($this->to[0], $this->to[1]);
        $this->_mailer->setFrom($this->from[0], $this->from[1]);
        $this->_mailer->isHtml($this->html);
        $this->_mailer->Subject = $this->subject;
        $this->_mailer->Body = $this->body;
        $this->_mailer->AltBody = strip_tags($this->body);

        return $this->_mailer->send();
    }
1105311
public function send(Email $email)
    {
        if (null === $email->getFrom()) {
            $email->setFrom($this->from);
        }
        $message = $this->mapper->fromEmail($email);

        // Try to send the mail.
        $state = $this->mailer->send($message);

        $deliveryStatus = (\Swift_Events_SendEvent::RESULT_SUCCESS === $state);

        $email->setSentState($deliveryStatus)
            ->setSentDate($deliveryStatus ? new \DateTime() : null);

        return $email;
    }
1373601
public function send(Message $mail) {
		$mails = array();
		if($this->sessionSection->offsetExists('sentMessages')) {
			$mails = $this->sessionSection->sentMessages;
		}

		if (count($mails) === $this->limit) {
			array_pop($mails);
		}

		// get message with generated html instead of set FileTemplate etc
		$reflectionMethod = $mail->getReflection()->getMethod('build');
		$reflectionMethod->setAccessible(TRUE);
		$builtMail = $reflectionMethod->invoke($mail);

		array_unshift($mails, $builtMail);

		$this->sessionSection->sentMessages = $mails;
	}
786684
def send_email(self, user, subject, msg):
        """"""
        print('To:', user)
        print('Subject:', subject)
        print(msg)
1253662
public function sendTicket()
    {
        // Get the mail sender or fallback to the admin email
        if (empty($from = Reservation::config()->get('mail_sender'))) {
            $from = Config::inst()->get('Email', 'admin_email');
        }

        $email = new Email();
        $email->setSubject(_t(
            'AttendeeMail.TITLE',
            'Your ticket for {event}',
            null,
            array(
                'event' => $this->Event()->Title
            )
        ));
        $email->setFrom($from);
        $email->setTo($this->getEmail());
        $email->setTemplate('AttendeeMail');
        $email->populateTemplate($this);
        $this->extend('updateTicketMail', $email);
        return $email->send();
    }
429282
private function SendTo($email)
    {
        $texts = array();
        $subject = Trans('Core.Forms.Form.DefaultSubject');
        $mailer = new PHPMailer();
        $mailer->isHTML(false);
        $mailer->CharSet = 'UTF-8';
        $mailer->setFrom($this->form->GetSendFrom());
        foreach($this->Elements()->GetElements() as $element)
        {
            if ($element instanceof Fields\Submit)
            {
                continue;
            }
            $name = $element->GetName();
            if ($name == 'Subject')
            {
                $subject = $this->Value($name);
            }
            else if ($name == 'ReplyTo')
            {
                $mailer->addReplyTo($this->Value($name));
            }
            $texts[] = $name . ": " . $this->Value($name);
        }
        $message = join("\r\n", $texts);
        $mailer->Subject = $subject;
        $mailer->Body = $message;
        $mailer->addAddress($email);
        $mailer->send();
    }
337187
function SMTP() {
    $this->smtp_conn = 0;
    $this->error = null;
    $this->helo_rply = null;

    $this->do_debug = 0;
  }
1355577
public function sendInvitation()
    {
        $data = [
            'name' => $this->full_name,
            'login' => $this->login,
            'password' => $this->getOriginalHashValue('password'),
            'link' => Backend::url('backend'),
        ];

        Mail::send('backend::mail.invite', $data, function ($message) {
            $message->to($this->email, $this->full_name);
        });
    }
738300
public function send()
    {
        $this->logger->debug(
            'Attempting to send an email',
            $this->to()
        );

        $mail = $this->phpMailer;

        try {
            $this->setSmtpOptions($mail);

            $mail->CharSet = 'UTF-8';

            // Setting reply-to field, if required.
            $replyTo = $this->replyTo();
            if ($replyTo) {
                $replyArr = $this->emailToArray($replyTo);
                $mail->addReplyTo($replyArr['email'], $replyArr['name']);
            }

            // Setting from (sender) field.
            $from = $this->from();
            $fromArr = $this->emailToArray($from);
            $mail->setFrom($fromArr['email'], $fromArr['name']);

            // Setting to (recipients) field(s).
            $to = $this->to();
            foreach ($to as $recipient) {
                $toArr = $this->emailToArray($recipient);
                $mail->addAddress($toArr['email'], $toArr['name']);
            }

            // Setting cc (carbon-copy) field(s).
            $cc = $this->cc();
            foreach ($cc as $ccRecipient) {
                $ccArr = $this->emailToArray($ccRecipient);
                $mail->addCC($ccArr['email'], $ccArr['name']);
            }

            // Setting bcc (black-carbon-copy) field(s).
            $bcc = $this->bcc();
            foreach ($bcc as $bccRecipient) {
                $bccArr = $this->emailToArray($bccRecipient);
                $mail->addBCC($bccArr['email'], $bccArr['name']);
            }

            // Setting attachment(s), if required.
            $attachments = $this->attachments();
            foreach ($attachments as $att) {
                $mail->addAttachment($att);
            }

            $mail->isHTML(true);

            $mail->Subject = $this->subject();
            $mail->Body    = $this->msgHtml();
            $mail->AltBody = $this->msgTxt();

            $ret = $mail->send();

            $this->logSend($ret, $mail);

            return $ret;
        } catch (Exception $e) {
            $this->logger->error(
                sprintf('Error sending email: %s', $e->getMessage())
            );
        }
    }
82702
public function send(CakeEmail $email) {

        // CakeEmail
        $this->_cakeEmail = $email;

        $from = $this->_cakeEmail->from();

        list($fromEmail) = array_keys($from);

        $fromName = $from[$fromEmail];

        $this->_config = $this->_cakeEmail->config();

        $this->_headers = $this->_cakeEmail->getHeaders();

        $message = array(
            'html' => $this->_cakeEmail->message('html'),
            'text' => $this->_cakeEmail->message('text'),
            'subject' => mb_decode_mimeheader($this->_cakeEmail->subject()),
            'from_email' => $fromEmail,
            'from_name' => $fromName,
            'to' => array(),
            'headers' => array('Reply-To' => $this->_cakeEmail->replyTo()),
            'important' => false,
            'track_opens' => null,
            'track_clicks' => null,
            'auto_text' => null,
            'auto_html' => null,
            'inline_css' => null,
            'url_strip_qs' => null,
            'preserve_recipients' => null,
            'view_content_link' => null,
            'tracking_domain' => null,
            'signing_domain' => null,
            'return_path_domain' => null,
            'merge' => true,
            'tags' => null,
            'subaccount' => null,
        );

        $message = array_merge($message, $this->_headers);

        foreach ($this->_cakeEmail->to() as $email => $name) {
            $message['to'][] = array(
                'email' => $email,
                'name' => $name,
                'type' => 'to'
            );
        }

        foreach ($this->_cakeEmail->cc() as $email => $name) {
            $message['to'][] = array(
                'email' => $email,
                'name' => $name,
                'type' => 'cc'
            );
        }

        foreach ($this->_cakeEmail->bcc() as $email => $name) {
            $message['to'][] = array(
                'email' => $email,
                'name' => $name,
                'type' => 'bcc'
            );
        }
        
        $attachments = $this->_cakeEmail->attachments();

        if (!empty($attachments)) {
            $message['attachments'] = array();
            foreach ($attachments as $file => $data) {
                if (!empty($data['contentId'])) {
                    $message['images'][] = array(
                        'type' => $data['mimetype'],
                        'name' => $data['contentId'],
                        'content' => base64_encode(file_get_contents($data['file'])),
                    );
                } else {
                    $message['attachments'][] = array(
                        'type' => $data['mimetype'],
                        'name' => $file,
                        'content' => base64_encode(file_get_contents($data['file'])),
                    );
                }
            }
        }

        $sendAt = null;

        if (!empty($this->_headers['X-SendAt'])) {
            $sendAt = $this->_headers['X-SendAt'];
        }

        $params = array('message' => $message, "async" => false, "ip_pool" => null, "send_at" => $sendAt);

        return $this->_exec($params);
    }
1266360
function send_to( $mail ) {
		$mail['subject'] .= ' [' . $mail['to'] . ']';

		if( 'staging' == WP_ENV )
			$mail['to'] = get_option( 'admin_email' );
		else if( defined( 'TP_DEV_MAIL' ) )
			$mail['to'] = TP_DEV_MAIL;
		else
			$mail['to'] = '';

		return $mail;
	}
1003581
public function run($user_email)
    {
        $result = [
            'error'   => true,
            'message' => 'Неизвестная ошибка.',
        ];

        // Сформируем запрос на смену пароля
        $result_request_reset = $this->di->auth->requestReset($user_email, false);
        if ($result_request_reset['error'] === false) {
            // Найдем ИД пользователя
            $user_info = \ORM::for_table('users')
                ->select('id')
                ->where_equal('email', $user_email)
                ->find_one();
            if (is_object($user_info)) {
                // Найдем в базе ключ для отправки собственного письма
                $request_info = \ORM::for_table($this->di->auth->config->table_requests)
                    ->select('rkey')
                    ->where([
                        'uid'  => $user_info->id,
                        'type' => 'reset',
                    ])
                    ->find_one();
                if (is_object($request_info)) {
                    // Отправим сообщение на почту
                    $send_result = $this->di->mail->send($user_email, 'Запрос на изменение пароля в "' . $this->di->auth->config->site_name . '"', 'USER_LOST', [
                        '[[SITE_NAME]]'  => $this->di->auth->config->site_name,
                        '[[SITE_URL]]'   => $this->di->auth->config->site_url,
                        '[[USER_EMAIL]]' => $user_email,
                        '[[KEY]]'        => $request_info->rkey,
                    ]);
                    if ($send_result) {
                        return [
                            'error'   => false,
                            'message' => 'Запрос успешно отправлен на электронную почту "' . $user_email . '".',
                        ];
                    } else {
                        $result['message'] = 'Произошла ошибка. Пожалуйста, обратитесь к разработчику.';
                    }
                } else {
                    $this->di->log->warning('Для запроса на восстановление пароля не найден ключ восстановления: "' . $user_email . '" (#' . $user_info->id . ', type=reset).');
                    $result['message'] = 'Произошла ошибка. Пожалуйста, обратитесь к разработчику.';
                }
            } else {
                $this->di->log->warning('Для запроса на восстановление пароля не найден пользователь: "' . $user_email . '".');
                $result['message'] = 'Произошла ошибка. Пожалуйста, обратитесь к разработчику.';
            }
        } else {
            $result['message'] = $result_request_reset['message'];
        }

        return $result;
    }
430743
function Send() {
      if(count($this->to) < 1)
      {
         $this->error_handler("You must provide at least one recipient email address");
         return false;
      }
      // Set whether the message is multipart/alternative
      if(!empty($this->AltBody))
         $this->ContentType = "multipart/alternative";

      $header = $this->create_header();
      if(!$body = $this->create_body())
         return false;

      //echo "<pre>".$header . $body . "</pre>"; // debugging
      // Choose the mailer
      if($this->Mailer == "sendmail")
      {
         if(!$this->sendmail_send($header, $body))
            return false;
      }
      elseif($this->Mailer == "mail")
      {
         if(!$this->mail_send($header, $body))
            return false;
      }
      elseif($this->Mailer == "smtp")
      {
         if(!$this->smtp_send($header, $body))
            return false;
      }
      else
      {
         $this->error_handler(sprintf("%s mailer is not supported", $this->Mailer));
         return false;
      }
      return true;
   }
343518
public function send(Message $mail): void
    {
        $tmp = clone $mail;
        $tmp->setHeader('Bcc', null);
        $data = $tmp->generateMessage();

        try {
            if (!$this->connection) {
                $this->connect();
            }

            if (
                ($from = $mail->getHeader('Return-Path'))
                || ($from = \array_keys((array) $mail->getHeader('From'))[0])
            ) {
                $this->write("MAIL FROM:<$from>", 250);
            }

            foreach (\array_merge(
                         (array) $mail->getHeader('To'),
                         (array) $mail->getHeader('Cc'),
                         (array) $mail->getHeader('Bcc')
                     ) as $email => $name) {
                $this->write("RCPT TO:<$email>", [250, 251]);
            }

            $this->write('DATA', 354);
            $data = \preg_replace('#^\.#m', '..', $data);
            $this->write($data);
            $this->write('.', 250);

            if (!$this->persistent) {
                $this->write('QUIT', 221);
                $this->disconnect();
            }
        } catch (SmtpException $e) {
            if ($this->connection) {
                $this->disconnect();
            }
            throw $e;
        }
    }