Get the "from" contact which the email will be sent from.

@param int $sendoption send email from constant ENROL_SEND_EMAIL_FROM_*
@param $context context where the user will be fetched
@return mixed|stdClass the contact user object.
181912
public function get_welcome_email_contact($sendoption, $context) {
        global $CFG;

        $contact = null;
        // Send as the first user assigned as the course contact.
        if ($sendoption == ENROL_SEND_EMAIL_FROM_COURSE_CONTACT) {
            $rusers = array();
            if (!empty($CFG->coursecontact)) {
                $croles = explode(',', $CFG->coursecontact);
                list($sort, $sortparams) = users_order_by_sql('u');
                // We only use the first user.
                $i = 0;
                do {
                    $allnames = get_all_user_name_fields(true, 'u');
                    $rusers = get_role_users($croles[$i], $context, true, 'u.id,  u.confirmed, u.username, '. $allnames . ',
                    u.email, r.sortorder, ra.id', 'r.sortorder, ra.id ASC, ' . $sort, null, '', '', '', '', $sortparams);
                    $i++;
                } while (empty($rusers) && !empty($croles[$i]));
            }
            if ($rusers) {
                $contact = array_values($rusers)[0];
            }
        } else if ($sendoption == ENROL_SEND_EMAIL_FROM_KEY_HOLDER) {
            // Send as the first user with enrol/self:holdkey capability assigned in the course.
            list($sort) = users_order_by_sql('u');
            $keyholders = get_users_by_capability($context, 'enrol/self:holdkey', 'u.*', $sort);
            if (!empty($keyholders)) {
                $contact = array_values($keyholders)[0];
            }
        }

        // If send welcome email option is set to no reply or if none of the previous options have
        // returned a contact send welcome message as noreplyuser.
        if ($sendoption == ENROL_SEND_EMAIL_FROM_NOREPLY || empty($contact)) {
            $contact = core_user::get_noreply_user();
        }

        return $contact;
    }
94151
protected static function _getValue($from, $subject) {
		$cached = static::_getCache($from, $subject);
		if (isset($cached)) {
			return $cached;
		}

		$value = null;
		switch (true) {
			case is_array($subject):
				$value = Set::get($subject, $from);
				break;
			case is_object($subject) && is_string($from):
				if (isset($subject->$from)) {
					$value = $subject->$from;
				} elseif (method_exists($subject, $from)) {
					$value = $subject->{$from}();
				} else {
					throw new InvalidArgumentException('Method or attribute does not exists: ' . $from);
				}
				break;
			case is_numeric($subject) || is_string($subject):
				$value = $subject;
				break;
			case is_callable($from):
				$value = call_user_func($from, $subject);
				break;
			default:
				throw new InvalidArgumentException('Wrong type combination: subject -> ' . gettype($subject) . ', from -> ' . gettype($from));
		}

		if (is_array($value)) {
			$value = count($value);
		}
		static::_setCache($from, $subject, $value);
		return $value;
	}
1163305
public function route(SendOptions $options, $messageClass)
    {
        $destination = $options->isRoutedToLocalInstance() ? $this->localAddress : null;
        $destination = $options->getExplicitDestination() ?: $destination;

        if ($destination === null || $destination === '') {
            $messageTypes = array_merge([$messageClass], array_values(class_implements($messageClass, true)));
            $endpointNames = $this->unicastRoutingTable->getEndpointNamesFor($messageTypes);
            $destinations = [];
            foreach ($endpointNames as $endpointName) {
                $destinations[] = $this->transportInfrastructure->toTransportAddress($endpointName);
            }
        } else {
            $destinations = [$destination];
        }

        $addressTags = [];
        foreach ($destinations as $destination) {
            $addressTags[] = new UnicastAddressTag($destination);
        }

        return $addressTags;
    }
528804
public function setCurlOption(int $optionName, $optionValue): RequestContext
    {
        if (@curl_setopt(curl_init(), $optionName, $optionValue)) {
            $this->curlOptions[$optionName] = $optionValue;
        } else {
            throw new RequestContextException(
                "Curl option is invalid: '$optionName' => " . var_export($optionValue, true)
            );
        }

        return $this;
    }
627739
public function From($SenderEmail = '', $SenderName = '', $bOverrideSender = FALSE) {
      if ($SenderEmail == '') {
         $SenderEmail = C('Garden.Email.SupportAddress', '');
         if (!$SenderEmail) {
            $SenderEmail = 'noreply@'.Gdn::Request()->Host();
         }
      }

      if ($SenderName == '')
         $SenderName = C('Garden.Email.SupportName', C('Garden.Title', ''));
      
      if($this->PhpMailer->Sender == '' || $bOverrideSender) $this->PhpMailer->Sender = $SenderEmail;
      
      ob_start();
      $this->PhpMailer->SetFrom($SenderEmail, $SenderName, FALSE);
      ob_end_clean();
      return $this;
   }
1306499
public function createReplyContext(
        $message,
        ReplyOptions $options,
        IncomingContext $parentContext
    ) {
        return new OutgoingReplyContext(
            new OutgoingLogicalMessage($message),
            $options,
            $parentContext->getIncomingPhysicalMessage(),
            $parentContext->getPendingTransportOperations(),
            $parentContext
        );
    }
665004
public function getUserOption($option, $defaultValue=null) {
    return isset($this->_options[$option])
        ? $this->_options[$option]
        : $defaultValue;
  }
624629
public function sendEstimate($deliveryMethodOrOptions = SendInvoiceOptions::METHOD_EMAIL)
    {
        if (is_string($deliveryMethodOrOptions)) {
            $options = new SendInvoiceOptions($deliveryMethodOrOptions);
        } else {
            $options = $deliveryMethodOrOptions;
        }
        unset($deliveryMethodOrOptions);

        if (! $options instanceof SendInvoiceOptions) {
            $options = is_object($options) ? get_class($options) : gettype($options);
            throw new InvalidArgumentException("Expected string or options instance. Received: '$options'");
        }

        $this->connection->patch($this->endpoint . '/' . $this->id . '/send_estimate', json_encode([
            'estimate_sending' => $options->jsonSerialize(),
        ]));

        return $this;
    }
716441
protected void sendEmail(TaskRuntimeContext context, String outcome)
    throws ObserverException {
        TaskInstance taskInstance = context.getTaskInstance();
        TemplatedEmail templatedEmail = new TemplatedEmail();
        templatedEmail.setFromAddress(getFromAddress());
        templatedEmail.setSubject(getSubject(taskInstance, outcome));
        templatedEmail.setHtml(true);
        templatedEmail.setTemplateAssetVerSpec(getTemplateSpec());
        templatedEmail.setRuntimeContext(context);

        try {
            List<Address> recipients = getRecipientAddresses(outcome);
            List<Address> ccRecipients = getCcRecipientAddresses(outcome);

            if (templatedEmail.getTemplateBody().contains("${taskActionUrl}")) {

                // send individual e-mails
                for (Address recip : recipients) {
                    String cuid = recip.toString().substring(0, recip.toString().indexOf('@'));
                    String userIdentifier = MiniCrypter.encrypt(cuid);
                    taskInstance.setUserIdentifier(userIdentifier);
                    templatedEmail.setRecipients(new Address[]{recip});
                    templatedEmail.setCcRecipients(new Address[0]);
                    try {
                        templatedEmail.sendEmail();
                    }
                    catch (MessagingException ex) {
                        logger.severeException(ex.getMessage(), ex);  // do not rethrow
                    }
                }
                if (ccRecipients != null) {
                    for (Address ccRecip : ccRecipients) {
                        String cuid = ccRecip.toString().substring(0, ccRecip.toString().indexOf('@'));
                        String userIdentifier = MiniCrypter.encrypt(cuid);
                        taskInstance.setUserIdentifier(userIdentifier);
                        templatedEmail.setRecipients(new Address[0]);
                        templatedEmail.setCcRecipients(new Address[]{ccRecip});
                        try {
                            templatedEmail.sendEmail();
                        }
                        catch (MessagingException ex) {
                            logger.severeException(ex.getMessage(), ex);  // do not rethrow
                        }
                    }
                }
            }
            else {
                if ((recipients != null && !recipients.isEmpty()) || (ccRecipients != null && !ccRecipients.isEmpty())) {
                    if (recipients != null)
                        templatedEmail.setRecipients(recipients.toArray(new Address[0]));
                    if (ccRecipients != null)
                        templatedEmail.setCcRecipients(ccRecipients.toArray(new Address[0]));
                    try {
                        templatedEmail.sendEmail();
                    }
                    catch (MessagingException ex) {
                        logger.severeException(ex.getMessage(), ex);  // do not rethrow
                    }
                }
                else {
                    logger.warn("WARNING: No email recipients for task " + context.getTaskInstanceId() + " " + outcome);
                }
            }
        }
        catch (Exception ex) {
            logger.severeException(ex.getMessage(), ex);
            throw new ObserverException(-1, ex.getMessage(), ex);
        }
    }
328150
protected function getRecipientIndex(array $context): int
    {
        $recipientIndex = 0;

        if (isset($context['recipient_index']) && \is_int($context['recipient_index'])) {
            $recipientIndex = $context['recipient_index'];
        }

        return $recipientIndex;
    }
853937
public function sendEmail($emailFrom, $fromName, $emailTo, $toName = '', $replyTo = null, $subject, $message_html, $message_text = null, $transportConfig = null) {

	    $html = new MimePart($message_html);
	    $html->type = 'text/html';

	    $body = new MimeMessage();
	    
	    if ($message_text!=null){
	        
	        // Add Alternative Email Text Content
    	    $text = new MimePart($message_text);
    	    $text->type = 'text/plain';
    	    
    	    $body->addPart($html,$text);
    	    
	    }else{
	        $body->addPart($html);
	    }
	    
	    $message = new Message();
	    $message->setFrom($emailFrom, $fromName);
	    $message->addTo($emailTo);
	    $message->setSubject($subject);
	    $message->setEncoding('UTF-8');
	    $message->setSender($emailTo, $toName);
	    $message->setBody($body);
	    if ($replyTo!=null){
	        $message->addReplyTo($replyTo);
	    }

        $transport = new Sendmail();

        if(is_array($transportConfig) && $transportConfig) {
            /**
             * Program executes these lines when user passes
             * custom Transport Configuration Options ($transportConfig)
             * to specify their own Mailing Service Provider
             */
            try{
                // Setup SMTP transport using LOGIN authentication
                $transport = new SmtpTransport();
                $options   = new SmtpOptions(array(
                    'name'              => $transportConfig['name'],
                    'host'              => $transportConfig['host'],
                    'connection_class'  => $transportConfig['connectionClass'],
                    'connection_config' => array(
                        'username' => $transportConfig['username'],
                        'password' => $transportConfig['password'],
                        'ssl' => $transportConfig['ssl'],
                    ),
                    'port' => $transportConfig['port'],
                ));
                $transport->setOptions($options);
            }
            catch (\Exception $exception){
                throw new \Exception($exception->getMessage());
            }
        }

        $transport->send($message);
	}
937819
public function optionRequired($requiredOption, InputInterface $input)
    {
        if (!empty($input->getOption($requiredOption))) {
            $requiredOptionValue = $input->getOption($requiredOption);
        } else {
            throw new \InvalidArgumentException('No --' . $requiredOption . ' option set.', 1458937128560);
        }
        return $requiredOptionValue;
    }
744707
public function isDifferentEmail(ExecutionContextInterface $context)
    {
        if ($this->getEmail() == $this->getFrom()->getEmail()) {
            $context->buildViolation('You can\'t invite yourself!')
                    ->atPath('email')
                    ->addViolation();
        }
    }
589122
def sendContact(self, context={}):
    
    for recipient in self.recipients:
      super(ContactFormMail, self).__init__(recipient, self.async)
      self.sendEmail('contactForm', 'New contact form message', context)
385489
protected function _minuteSelect($options, $context)
    {
        $options += [
            'name' => '',
            'val' => null,
            'interval' => 1,
            'round' => 'up',
            'leadingZeroKey' => true,
            'leadingZeroValue' => true,
            'templateVars' => [],
        ];
        $options['interval'] = max($options['interval'], 1);
        if (empty($options['options'])) {
            $options['options'] = $this->_generateNumbers(0, 59, $options);
        }

        unset(
            $options['leadingZeroKey'],
            $options['leadingZeroValue'],
            $options['interval'],
            $options['round']
        );

        return $this->_select->render($options, $context);
    }
22539
public function getContextually($option, ConnectionKey $connectionKey = null)
    {
        $original = $this->configuration->get($option);
        $connectionKey = $connectionKey ?: $this->connections->getCurrentConnectionKey();

        $contexts = ['stages', 'connections', 'servers'];
        foreach ($contexts as $context) {
            if ($contextual = $this->getForContext($option, $context, $original, $connectionKey)) {
                return $contextual;
            }
        }

        return $original;
    }
104068
public function addContextContact(Contact $contact = null)
    {
        if (!$contact) {
            return $this;
        }
        $context = [];
        $conType = [];

        // Append contact ID.
        $contactId     = (int) $contact->getId();
        $context['id'] = isset($contactId) ? $contactId : null;
        $conType['id'] = 'number';

        // Append contact owner data.
        $owner                         = $contact->getOwner();
        $context['owner']              = [];
        $context['owner']['id']        = $owner ? $owner->getId() : null;
        $conType['owner']['id']        = 'number';
        $context['owner']['username']  = $owner ? $owner->getUsername() : null;
        $context['owner']['firstName'] = $owner ? $owner->getFirstName() : null;
        $context['owner']['lastName']  = $owner ? $owner->getLastName() : null;
        $context['owner']['email']     = $owner ? $owner->getEmail() : null;

        // Append points value.
        $points            = $contact->getPoints();
        $context['points'] = isset($points) ? $points : null;
        $conType['points'] = 'number';

        // Append IP Addresses.
        $context['ipAddresses'] = [];
        $context['ip']          = null;
        foreach ($contact->getIpAddresses()->toArray() as $ip => $value) {
            $context['ipAddresses'][] = $ip;
            $context['ip']            = $ip;
        }

        // Add Identified date.
        /** @var \DateTime $dateIdentified */
        $dateIdentified            = $contact->getDateIdentified();
        $context['dateIdentified'] = $dateIdentified ? $this->dateFormatHelper->format($dateIdentified) : null;
        $conType['dateIdentified'] = 'datetime';

        // Add Modified date.
        /** @var \DateTime $dateModified */
        $dateModified            = $contact->getDateModified();
        $context['dateModified'] = $dateModified ? $this->dateFormatHelper->format($dateModified) : null;
        $conType['dateModified'] = 'datetime';

        // Add DNC data.
        $context['doNotContacts'] = [];
        $context['doNotContact']  = false;
        if ($contactId && $this->needsDncData) {
            /** @var \Mautic\LeadBundle\Model\DoNotContact $record */
            foreach ($contact->getDoNotContact() as $record) {
                $context['doNotContacts'][$record->getChannel()]           = [
                    'comments' => $record->getComments(),
                    'reason'   => $record->getReason(),
                    'exists'   => true,
                ];
                $conType['doNotContacts'][$record->getChannel()]['exists'] = 'boolean';
                $context['doNotContact']                                   = true;
            }
            $conType['doNotContact'] = 'boolean';
        }

        // Add UTM data.
        $context['utm'] = [
            'campaign'   => null,
            'content'    => null,
            'medium'     => null,
            'query'      => null,
            'referrer'   => null,
            'remoteHost' => null,
            'source'     => null,
            'term'       => null,
            'url'        => null,
            'userAgent'  => null,
        ];
        if ($contactId && $this->needsUtmData) {
            $utmTags            = $this->utmSourceHelper->getSortedUtmTags($contact);
            $context['utmTags'] = [];
            if ($utmTags) {
                foreach ($utmTags as $utmTag) {
                    $tags                 = [
                        'campaign'   => $utmTag->getUtmCampaign(),
                        'content'    => $utmTag->getUtmContent(),
                        'medium'     => $utmTag->getUtmMedium(),
                        'query'      => $utmTag->getQuery(),
                        'referrer'   => $utmTag->getReferer(),
                        'remoteHost' => $utmTag->getRemoteHost(),
                        'source'     => $utmTag->getUtmSource(),
                        'term'       => $utmTag->getUtmTerm(),
                        'url'        => $utmTag->getUrl(),
                        'userAgent'  => $utmTag->getUserAgent(),
                    ];
                    $context['utmTags'][] = $tags;
                    // Override the {{ utm.values }} to be the latest non-empty version of each found.
                    foreach ($tags as $key => $value) {
                        if (!empty($value)) {
                            $context['utm'][$key] = $value;
                        }
                    }
                }
            }
        }

        // Add Device data.
        $context['device'] = [
            'name'        => null,
            'brand'       => null,
            'model'       => null,
            'fingerprint' => null,
            'trackingId'  => null,
            'os'          => [
                'osName'      => null,
                'osShortName' => null,
                'osVersion'   => null,
                'osPlatform'  => null,
            ],
        ];
        if ($contactId && $this->needsDeviceData) {
            /** @var LeadDeviceRepository $deviceRepo */
            $deviceRepo = $this->contactModel->getDeviceRepository();
            $devices    = $deviceRepo->getEntities(
                [
                    'limit'            => 1,
                    'orderBy'          => $deviceRepo->getTableAlias().'.id',
                    'orderByDir'       => 'DESC',
                    'filter'           => [
                        'force' => [
                            [
                                'column' => 'IDENTITY('.$deviceRepo->getTableAlias().'.lead)',
                                'expr'   => 'eq',
                                'value'  => $contactId,
                            ],
                        ],
                    ],
                    'ignore_paginator' => true,
                ]
            );
            if ($devices && $device = reset($devices)) {
                $context['device'] = [
                    'name'        => $device->getDevice(),
                    'brand'       => $device->getDeviceBrand(),
                    'model'       => $device->getDeviceModel(),
                    'fingerprint' => $device->getDeviceFingerprint(),
                    'trackingId'  => $device->getTrackingId(),
                    'os'          => [
                        'osName'      => $device->getDeviceOsName(),
                        'osShortName' => $device->getDeviceOsShortName(),
                        'osVersion'   => $device->getDeviceOsVersion(),
                        'osPlatform'  => $device->getDeviceOsPlatform(),
                    ],
                ];
            }
        }

        $fieldGroups = $contact->getFields();
        if ($fieldGroups) {
            foreach ($fieldGroups as $fgKey => $fieldGroup) {
                foreach ($fieldGroup as $fkey => $field) {
                    $value = isset($field['value']) ? $field['value'] : '';
                    $type  = isset($field['type']) ? $field['type'] : '';
                    if ('' !== $value && in_array($type, ['datetime', 'date', 'time'])) {
                        // Soft support for labels/values as dates/times.
                        @$newValue = $this->dateFormatHelper->format($value);
                        if (null !== $newValue && '' !== $newValue) {
                            $value = $newValue;
                        }
                    }
                    $context[$fkey] = $value;
                    if ($type) {
                        $conType[$fkey] = $type;
                    }
                }
            }
        }

        // Support multiple contacts in the future if needed by uncommenting a bit here.
        // $contacts = !empty($this->context['contacts']) ? $this->context['contacts'] : [];

        // Set the context to this contact.
        $this->sanitizeContext($context);
        $this->context = array_merge($this->context, $context);
        $this->conType = array_merge($this->conType, $conType);

        // Support multiple contacts for future batch processing.
        // $this->context['contacts']                 = $contacts;
        // $this->context['contacts'][$context['id']] = $context;

        return $this;
    }