Connect to mail server and send actual email
964133
def send_mail(self, event):
        """"""

        mime_mail = MIMEText(event.text)
        mime_mail['Subject'] = event.subject

        if event.account == 'default':
            account_name = self.config.default_account
        else:
            account_name = event.account

        account = list(filter(lambda account: account['name'] == account_name, self.config.accounts))[0]

        mime_mail['From'] = render(account['mail_from'], {'server': account['server'], 'hostname': self.hostname})
        mime_mail['To'] = event.to_address

        self.log('MimeMail:', mime_mail, lvl=verbose)
        if self.config.mail_send is True:
            self.log('Sending mail to', event.to_address)

            self.fireEvent(task(send_mail_worker, account, mime_mail, event), "mail-transmit-workers")
        else:
            self.log('Not sending mail, here it is for debugging info:', mime_mail, pretty=True)
863933
def send(self, msg_string, immediate=True):
        
        try:
            mailhost = api.get_tool("MailHost")
            mailhost.send(msg_string, immediate=immediate)
        except SMTPException as e:
            logger.error(e)
            return False
        except socket.error as e:
            logger.error(e)
            return False
        return True
580232
private static function mail()
    {
        $files = ['Mail', 'Mailable', 'SMTP'];
        $folder = static::$root.'Mailing'.'/';

        self::call($files, $folder);

        $files = ['SmtpParameterNotFoundException', 'MailViewNotFoundException'];
        $folder = $folder.'Exceptions/';

        self::call($files, $folder);
    }
940384
def _send_mail(self, subject, template, enrollment, event):
        """"""

        context = {
            'name': enrollment.name,
            'invitation_url': self.invitation_url,
            'node_name': self.node_name,
            'node_url': self.node_url,
            'uuid': enrollment.uuid
        }

        mail = render(template, context)
        self.log('Mail:', mail, lvl=verbose)
        mime_mail = MIMEText(mail)
        mime_mail['Subject'] = render(subject, context)
        mime_mail['From'] = render(self.config.mail_from, {'hostname': self.hostname})
        mime_mail['To'] = enrollment.email

        self.log('MimeMail:', mime_mail, lvl=verbose)
        if self.config.mail_send is True:
            self.log('Sending mail to', enrollment.email)

            self.fireEvent(task(send_mail_worker, self.config, mime_mail, event), "enrolworkers")
        else:
            self.log('Not sending mail, here it is for debugging info:', mail, pretty=True)
993867
def send_mail(subject, message_plain, message_html, email_from, email_to,
              custom_headers={}, attachments=()):
    
    if not message_plain and not message_html:
        raise ValueError(_("Either message_plain or message_html should be not None"))

    if not message_plain:
        message_plain = html2text(message_html)

    message = {}

    message['subject'] = subject
    message['body'] = message_plain
    message['from_email'] = email_from
    message['to'] = email_to
    if attachments:
        message['attachments'] = attachments
    if custom_headers:
        message['headers'] = custom_headers

    msg = EmailMultiAlternatives(**message)
    if message_html:
        msg.attach_alternative(message_html, "text/html")
    msg.send()
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;
  }
902827
def _send_email(name, email):
    ""
    config = __salt__['config.option']('splunk')
    email_object = config.get('email')
    if email_object:
        cc = email_object.get('cc')
        subject = email_object.get('subject')
        message = email_object.get('message').format(name, name, _generate_password(email), name)

        try:
            mail_process = subprocess.Popen(['mail', '-s', subject, '-c', cc, email], stdin=subprocess.PIPE)
        except Exception as e:
            log.error("unable to send email to %s: %s", email, e)

        mail_process.communicate(message)

        log.info("sent account creation email to %s", email)
785253
def sendmail(array):
    
    username = 'root@robin8.io'
    FROM = username
    TO = [array["to"]]
    SUBJECT = array["subject"]
    # check on correct data in optional
    if type(array["optional"]) == str and array["optional"]:
        TEXT = array["optional"]
    else:
        return "Error: missed argument"
    # make template
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP('localhost')
        logging.info(server)
        #server.ehlo()
        #server.starttls()
        # authorizing user, must setup your account
        #server.login(username, password)
        # send mail
        server.sendmail(FROM, TO, message)
        server.quit()
        logging.info(message)
        return "Success"
    except:
        return "Error"
704953
def sendmail(self, to, message):
        

        # If we were passed a bare string as the To: address, convert it to
        # a single element list.
        if isinstance(to, str):
            to = [ to, ]

        # Send one email with the appropriate recipient list.
        server = self._smtp_server()
        server.sendmail(self.get_rfc2822_address(), to, message)
        server.quit()
974370
def send(self, confirmation_email, send_date="immediately"):
        """"""
        body = {
            "ConfirmationEmail": confirmation_email,
            "SendDate": send_date}
        response = self._post(self.uri_for("send"), json.dumps(body))
1319837
def send(self, email, attachments=()):
        '''
        '''

        msg = email.as_mime(attachments)

        if 'From' not in msg:
            msg['From'] = self.sender_address()

        if self._conn:
            self._conn.sendmail(self.username, email.recipients,
                                msg.as_string())
        else:
            with self:
                self._conn.sendmail(self.username, email.recipients,
                                    msg.as_string())
849292
function sendMail(options) {

	var i = 0
	var cmds = [
		'HELO ' + options.host,

		// auth
		'auth login',
		new Buffer(options.username).toString('base64'),
		new Buffer(options.password).toString('base64'),

		// from to
		'mail from:' + options.username,
		CMD_RCPT_TO + options.to,

		// message
		'data',
		CMD_MESSAGE,

		'quit'
	]
	var message = [
		'from:' + options.from,
		'to:' + options.to,
		'subject:' + options.subject,
		'',
		options.body,
		'.'
	]

	prepairRcpt(cmds)

	var client = net.connect({
		host: options.host,
		port: options.port
	})

	client.on('connect', function () {
		console.log('connected')
	})

	client.on('data', function (data) {
		console.log('Serer: ' + data.toString().replace(END_LINE, ''))

		if (i >= cmds.length) {
			client.end()
			return
		}

		var cmd = cmds[i++]

		if (cmd === CMD_MESSAGE) {
			console.log('message body:')
			message.forEach(function (line) {
				console.log('> ' + line)
				client.write(line + END_LINE)
			})
		} else {
			console.log('ME: ' + cmd)
			client.write(cmd + END_LINE)
		}
	})

	client.on('error', function (er) {
		console.log('error: ' + er)
	})

	client.on('end', function () {
		console.log('send mail finish')
	})
}
1086926
def send_email(self):
        
        # send only if user notification setting is set to true
        if self.check_user_settings():
            send_mail(_(self.type), self.email_message, settings.DEFAULT_FROM_EMAIL, [self.to_user.email])
            return True
        else:
            # return false otherwise
            return False
1291167
def run(self, **kwargs):
        
        try:
            # connect to server and login
            box = imaplib.IMAP4_SSL(settings.IMAP_SERVER)
            box.login(settings.IMAP_USERNAME, settings.IMAP_PASSWORD)
            box.select()

            # search for all mails in the mailbox
            result, mail_indices = box.search(None, 'ALL')

            # if everything was ok...
            if result == 'OK':

                # check number of mails
                mail_count = len(mail_indices[0].split())
                logger.info('found %(mail_count)d mails...' % {'mail_count': mail_count})

                # iterate the mail indices and fetch the mails
                ips_created = 0
                for mail_index in mail_indices[0].split():
                    logger.info('fetching mail %(mail_index)s...' % {'mail_index': int(mail_index)})
                    # mail data is a list with a tuple
                    sub_result, mail_data = box.fetch(mail_index, '(BODY[TEXT])')
                    if sub_result == 'OK':

                        # fetch the ips
                        ips = list_remove_duplicates(
                            self.find_ips(''.join([str(data) for data in mail_data[0]]))
                        )

                        # if ips found, add them and delete the mail
                        if len(ips) > 0:
                            logger.info('found %(count)d IPs' % {'count': len(ips)})
                            ips_created += IP.batch_add_ips(ips)
                            box.store(mail_index, '+FLAGS', '\\Deleted')

                    else:
                        logger.error('fetching mail with index %(index)d failed' % {'index': mail_index})

                # finally, if ips were added, unify the IPs
                if ips_created > 0:
                    logger.info('created %(count)d IPs' % {'count': ips_created})
                    IP.unify_ips()

            else:
                logger.error('search returned not OK')

            box.close()
            box.logout()
        except:
            logger.exception('retrieving mail failed')
786684
def send_email(self, user, subject, msg):
        """"""
        print('To:', user)
        print('Subject:', subject)
        print(msg)
768679
def send_email_smtp(to, subject, html_content, config,
                    files=None, data=None, images=None, dryrun=False,
                    cc=None, bcc=None, mime_subtype='mixed'):
    
    smtp_mail_from = config.get('SMTP_MAIL_FROM')
    to = get_email_address_list(to)

    msg = MIMEMultipart(mime_subtype)
    msg['Subject'] = subject
    msg['From'] = smtp_mail_from
    msg['To'] = ', '.join(to)
    msg.preamble = 'This is a multi-part message in MIME format.'

    recipients = to
    if cc:
        cc = get_email_address_list(cc)
        msg['CC'] = ', '.join(cc)
        recipients = recipients + cc

    if bcc:
        # don't add bcc in header
        bcc = get_email_address_list(bcc)
        recipients = recipients + bcc

    msg['Date'] = formatdate(localtime=True)
    mime_text = MIMEText(html_content, 'html')
    msg.attach(mime_text)

    # Attach files by reading them from disk
    for fname in files or []:
        basename = os.path.basename(fname)
        with open(fname, 'rb') as f:
            msg.attach(
                MIMEApplication(
                    f.read(),
                    Content_Disposition="attachment; filename='%s'" % basename,
                    Name=basename))

    # Attach any files passed directly
    for name, body in (data or {}).items():
        msg.attach(
            MIMEApplication(
                body,
                Content_Disposition="attachment; filename='%s'" % name,
                Name=name,
            ))

    # Attach any inline images, which may be required for display in
    # HTML content (inline)
    for msgid, body in (images or {}).items():
        image = MIMEImage(body)
        image.add_header('Content-ID', '<%s>' % msgid)
        image.add_header('Content-Disposition', 'inline')
        msg.attach(image)

    send_MIME_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
572538
def send(self, test=None):
        '''
        
        '''
        self._check_values()

        # Set up message dictionary
        json_message = self.to_json_message()

        # if (self.__html_body and not self.__text_body) and self.__multipart:
        #     # TODO: Set up regex to strip html
        #     pass

        # If test is not specified, attempt to read the Django setting
        if test is None:
            try:
                from django.conf import settings as django_settings
                test = getattr(django_settings, "POSTMARK_TEST_MODE", None)
            except ImportError:
                pass

        # If this is a test, just print the message
        if test:
            print('JSON message is:\n%s' % json.dumps(json_message, cls=PMJSONEncoder))
            return

        if self.__template_id:
            endpoint_url = __POSTMARK_URL__ + 'email/withTemplate/'
        else:
            endpoint_url = __POSTMARK_URL__ + 'email'

        # Set up the url Request
        req = Request(
            endpoint_url,
            json.dumps(json_message, cls=PMJSONEncoder).encode('utf8'),
            {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-Postmark-Server-Token': self.__api_key,
                'User-agent': self.__user_agent
            }
        )

        # Attempt send
        try:
            # print 'sending request to postmark: %s' % json_message
            result = urlopen(req)
            jsontxt = result.read().decode('utf8')
            result.close()
            if result.code == 200:
                self.message_id = json.loads(jsontxt).get('MessageID', None)
                return True
            else:
                raise PMMailSendException('Return code %d: %s' % (result.code, result.msg))
        except HTTPError as err:
            if err.code == 401:
                raise PMMailUnauthorizedException('Sending Unauthorized - incorrect API key.', err)
            elif err.code == 422:
                try:
                    jsontxt = err.read().decode('utf8')
                    jsonobj = json.loads(jsontxt)
                    desc = jsonobj['Message']
                    error_code = jsonobj['ErrorCode']
                except KeyError:
                    raise PMMailUnprocessableEntityException('Unprocessable Entity: Description not given')

                if error_code == 406:
                    raise PMMailInactiveRecipientException('You tried to send email to a recipient that has been marked as inactive.')

                raise PMMailUnprocessableEntityException('Unprocessable Entity: %s' % desc)
            elif err.code == 500:
                raise PMMailServerErrorException('Internal server error at Postmark. Admins have been alerted.', err)
        except URLError as err:
            if hasattr(err, 'reason'):
                raise PMMailURLException('URLError: Failed to reach the server: %s (See "inner_exception" for details)' % err.reason, err)
            elif hasattr(err, 'code'):
                raise PMMailURLException('URLError: %d: The server couldn\'t fufill the request. (See "inner_exception" for details)' % err.code, err)
            else:
                raise PMMailURLException('URLError: The server couldn\'t fufill the request. (See "inner_exception" for details)', err)