Takes the recipients, body, and attachments of the Message and sends.

        Args:
            content_type: Can either be 'HTML' or 'Text', defaults to HTML.
322674
def send(self, content_type='HTML'):
        

        payload = self.api_representation(content_type)

        endpoint = 'https://outlook.office.com/api/v1.0/me/sendmail'
        self._make_api_call('post', endpoint=endpoint, data=json.dumps(payload))
99605
def send_mass_template_mail(subject_template, body_template, recipients, context=None):
    
    if context:
        subject, body = render_mail_template(subject_template, body_template, context)
    else:
        subject, body = subject_template, body_template

    message_tuples = [(subject, body, conf.get('DEFAULT_FROM_EMAIL'), [r]) for r in recipients]

    send_mass_mail(message_tuples)
1228003
def send_mail(subject, message, from_email, recipient_list, html_message='',
              scheduled_time=None, headers=None, priority=PRIORITY.medium):
    

    subject = force_text(subject)
    status = None if priority == PRIORITY.now else STATUS.queued
    emails = []
    for address in recipient_list:
        emails.append(
            Email.objects.create(
                from_email=from_email, to=address, subject=subject,
                message=message, html_message=html_message, status=status,
                headers=headers, priority=priority, scheduled_time=scheduled_time
            )
        )
    if priority == PRIORITY.now:
        for email in emails:
            email.dispatch()
    return emails
215078
private function sendHeaders()
    {
        if (!array_key_exists('Content-Type', $this->headers)) {
            $this->headers['Content-Type'] = 'text/html; charset=UTF-8';
        }

        $this->headers['Content-Length'] = strlen($this->body);

        header(
            sprintf(
                'HTTP/%s %s %s',
                $this->request->server('SERVER_PROTOCOL'),
                $this->numericStatusCode,
                $this->textualStatusCode ?: $this->statusCode->getText($this->numericStatusCode)
            ),
            true,
            $this->numericStatusCode
        );

        foreach ($this->headers as $key => $value) {
            header(sprintf('%s: %s', $key, $value));
        }
    }
273977
def send_text_file(self, text_file, sender=None, recipient=None):
        
        log = logging.getLogger(self.cls_logger + '.send_text_file')

        if not isinstance(text_file, basestring):
            msg = 'arg text_file must be a string, found type: {t}'.format(t=text_file.__class__.__name__)
            raise AssetMailerError(msg)

        if not os.path.isfile(text_file):
            msg = 'The provided text_file was not found or is not a file: {f}'.format(f=text_file)
            raise AssetMailerError(msg)

        # Determine sender/recipient
        if sender is None:
            sender = default_sender_email
        if recipient is None:
            recipient = self.recipient_email

        # Set the email subject
        file_name = text_file.split(os.path.sep)[-1]
        subject = self.subject + file_name

        # Read the input text file
        try:
            fp = open(text_file, 'rb')
            mail_message = MIMEText(fp.read())
            fp.close()
        except OSError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem reading text file: {f}\n{e}'.format(
                n=ex.__class__.__name__, f=text_file, e=str(ex))
            raise AssetMailerError, msg, trace

        # Configure the mail message
        mail_message['Subject'] = subject
        mail_message['From'] = sender
        mail_message['To'] = recipient

        # Configure the SMTP server
        log.debug('Configuring the SMTP server...')
        try:
            s = smtplib.SMTP(self.smtp_server)
        except (smtplib.SMTPConnectError, socket.timeout, socket.error):
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem connecting to SMTP server: {s}\n{e}'.format(
                n=ex.__class__.__name__, s=self.smtp_server, e=str(ex))
            raise AssetMailerError, msg, trace

        # Set the SMTP log level
        # s.set_debuglevel(debuglevel=__debug__)

        # Set the SMTP server to be localhost
        log.debug('Sending email with subject {s} to {e}...'.format(s=subject, e=recipient))
        try:
            s.sendmail(sender, [recipient], mail_message.as_string())
        except smtplib.SMTPRecipientsRefused:
            _, ex, trace = sys.exc_info()
            msg = '{n}: All recipients were refused, nobody got the mail: {r}:\n{e}'.format(
                n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPSenderRefused:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server did not accept the sender address: {s}:\n{e}'.format(
                n=ex.__class__.__name__, s=sender, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPHeloError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server did not respond to the HELO greeting\n{e}'.format(
                n=ex.__class__.__name__, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPDataError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server replied with an unexpected error code (other than a refusal of a recipient)\n{e}'.\
                format(n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPConnectError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a connection error\n{e}'. \
                format(n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        else:
            log.info('Sent email to: {r}'.format(r=recipient))
        finally:
            s.quit()
834702
public function addAttachment($filename, string $content_type = ''): Mailer
    {
        if(is_array($filename)) {
            $this->attachments[] = [
                'filename' => $filename['filename'],
                'content' => $filename['content'],
                'content_type' => $filename['content_type'] ?: ($content_type ?: 'application/octet-stream'),
            ];
        }else {
            $this->attachments[] = [
                'filename' => $filename,
                'content_type' => $content_type ?: MimeTypes::getMimeTypeByExt(strtolower(pathinfo($filename, PATHINFO_EXTENSION))),
            ];
        }

        return $this;
    }
391828
public void sendWithAttachment(String subject, 
                                 String textBody,
                                 String attachmentType,
                                 String attachmentName,
                                 InputStream is)
  {
    try {
      MimeMessage msg = new MimeMessage(getSession());

      if(_from.length > 0)
        msg.addFrom(_from);
      msg.addRecipients(RecipientType.TO, _to);
      if(subject != null)
        msg.setSubject(subject);
      
      // msg.setContent(textBody, "multipart/mime");
      
      MimeMultipart multipart = new MimeMultipart();
      
      MimeBodyPart textBodyPart = new MimeBodyPart();
      textBodyPart.setText(textBody);
      multipart.addBodyPart(textBodyPart);
      
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      TempBuffer tb = TempBuffer.create();
      byte []buffer = tb.buffer();
      int len;
      
      while ((len = is.read(buffer, 0, buffer.length)) >= 0) {
        bos.write(buffer, 0, len);
      }
      bos.close();
      byte []content = bos.toByteArray();
      TempBuffer.free(tb);
      
      DataSource dataSource
        = new ByteArrayDataSource(content, attachmentType);
      
      MimeBodyPart pdfBodyPart = new MimeBodyPart();
      pdfBodyPart.setDataHandler(new DataHandler(dataSource));
      pdfBodyPart.setFileName(attachmentName);
      multipart.addBodyPart(pdfBodyPart);
      
      msg.setContent(multipart);

      send(msg);
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
1228523
def to_message(self):
        

        self.validate()
        
        bodies = [(self.body, 'text/plain'), (self.html, 'text/html')]

        for idx, (val, content_type) in enumerate(bodies):
            if val is None:
                bodies[idx] = None
            elif isinstance(val, Attachment):
                bodies[idx] = val.to_mailbase(content_type)
            else:
                # presumed to be a textual val
                attachment = Attachment(
                    data=val,
                    content_type=content_type,
                    transfer_encoding='quoted-printable',
                    disposition='inline'
                    )
                bodies[idx] = attachment.to_mailbase(content_type)

        body, html = bodies

        base = MailBase([
            ('To', ', '.join(self.recipients)),
            ('From', self.sender),
            ('Subject', self.subject),
            ])

        # base represents the outermost mime part; it will be one of the
        # following types:
        #
        # - a multipart/mixed type if there are attachments.  this
        #   part will contain a single multipart/alternative type if there
        #   is both an html part and a plaintext part (the alternative part
        #   will contain both the text and html), it will contain
        #   a single text/plain part if there is only a plaintext part,
        #   or it will contain a single text/html part if there is only
        #   an html part.  it will also contain N parts representing
        #   each attachment as children of the base mixed type.
        #
        # - a multipart/alternative type if there are no attachments but
        #   both an html part and a plaintext part.  it will contain
        #   a single text/plain part if there is only a plaintext part,
        #   or it will contain a single text/html part if there is only
        #   an html part.
        #
        # - a text/plain type if there is only a plaintext part
        #
        # - a text/html type if there is only an html part

        if self.cc:
            base['Cc'] = ', '.join(self.cc)
            
        if self.extra_headers:
            base.update(dict(self.extra_headers))

        if self.attachments:
            base.set_content_type('multipart/mixed')
            altpart = MailBase()
            base.attach_part(altpart)
        else:
            altpart = base
            
        if body and html:
            altpart.set_content_type('multipart/alternative')
            altpart.set_body(None)
            # Per RFC2046, HTML part comes last in multipart/alternative
            altpart.attach_part(body)
            altpart.attach_part(html)
        elif body is not None:
            altpart.merge_part(body)
        elif html is not None:
            altpart.merge_part(html)

        for attachment in self.attachments:
            attachment_mailbase = attachment.to_mailbase()
            base.attach_part(attachment_mailbase)

        return to_message(base)
1349184
async def _send(self,
                    request: Request,
                    content: Dict[Text, Any],
                    stack: Stack):
        

        msg = {
            'recipient': {
                'id': request.conversation.fbid,
            },
            'message': content,
        }

        if stack and stack.has_layer(MessagingType):
            mt = stack.get_layer(MessagingType)
        else:
            mt = MessagingType(response=True)

        msg.update(mt.serialize())
        msg_json = ujson.dumps(msg)

        headers = {
            'content-type': 'application/json',
        }

        params = {
            'access_token': self._access_token(request),
        }

        post = self.session.post(
            MESSAGES_ENDPOINT,
            params=params,
            data=msg_json,
            headers=headers,
        )

        logger.debug('Sending: %s', msg_json)

        async with post as r:
            await self._handle_fb_response(r)
325378
def set_content(self, value: RequestContent, *,
                    content_type: str = None):
        '''
        
        '''
        assert self._attached_files is None, \
               'cannot set content because you already attached files.'
        guessed_content_type = 'application/octet-stream'
        if value is None:
            guessed_content_type = 'text/plain'
            self._content = b''
        elif isinstance(value, str):
            guessed_content_type = 'text/plain'
            self._content = value.encode('utf-8')
        else:
            guessed_content_type = 'application/octet-stream'
            self._content = value
        self.content_type = (content_type if content_type is not None
                             else guessed_content_type)
649386
def send_email(recipients, subject, text_content=None, html_content=None, from_email=None, use_base_template=True, category=None, fail_silently=False, language=None, cc=None, bcc=None, attachments=None, headers=None, bypass_queue=False, bypass_hijacking=False, attach_files=None):
    
    from django.conf import settings
    if not bypass_queue and hasattr(settings, 'MAILING_USE_CELERY') and settings.MAILING_USE_CELERY:
        from celery.execute import send_task
        return send_task('mailing.queue_send_email',[recipients, subject, text_content, html_content, from_email, use_base_template, category, fail_silently, language if language else translation.get_language(), cc, bcc, attachments, headers, bypass_hijacking, attach_files])
    else:

        header_category_value = '%s%s' % (settings.MAILING_HEADER_CATEGORY_PREFIX if hasattr(settings, 'MAILING_HEADER_CATEGORY_PREFIX') else '', category)
        # Check for sendgrid support and add category header
        # --------------------------------
        if hasattr(settings, 'MAILING_USE_SENDGRID'):
            send_grid_support = settings.MAILING_USE_SENDGRID
        else:
            send_grid_support = False

        if not headers:
            headers = dict()        
        if send_grid_support and category:
            headers['X-SMTPAPI'] = '{"category": "%s"}' % header_category_value

        # Check for Mailgun support and add label header
        # --------------------------------
        if hasattr(settings, 'MAILING_USE_MAILGUN'):
            mailgun_support = settings.MAILING_USE_MAILGUN
        else:
            mailgun_support = False

        if not headers:
            headers = dict()        
        if mailgun_support and category:
            headers['X-Mailgun-Tag'] = header_category_value


        # Ensure recipients are in a list
        # --------------------------------
        if isinstance(recipients, basestring):
            recipients_list = [recipients]
        else:
            recipients_list = recipients

        # Check if we need to hijack the email
        # --------------------------------
        if hasattr(settings, 'MAILING_MAILTO_HIJACK') and not bypass_hijacking:
            headers['X-MAILER-ORIGINAL-MAILTO'] = ','.join(recipients_list)
            recipients_list = [settings.MAILING_MAILTO_HIJACK]

        if not subject:
            raise MailerMissingSubjectError('Subject not supplied')

        # Send ascii, html or multi-part email
        # --------------------------------
        if text_content or html_content:
            if use_base_template:
                prev_language = translation.get_language()
                language and translation.activate(language)
                text_content = render_to_string('mailing/base.txt', {'mailing_text_body': text_content, 'mailing_subject': subject, 'settings': settings}) if text_content else None
                html_content = render_to_string('mailing/base.html', {'mailing_html_body': html_content, 'mailing_subject': subject, 'settings': settings}) if html_content else None
                translation.activate(prev_language)
            msg = EmailMultiAlternatives(subject, text_content if text_content else html_content, from_email if from_email else settings.DEFAULT_FROM_EMAIL, recipients_list, cc=cc, bcc=bcc, attachments=attachments, headers = headers)
            if html_content and text_content:
                msg.attach_alternative(html_content, "text/html")
            elif html_content: # Only HTML
                msg.content_subtype = "html"

            # Attach files through attach_files helper
            # --------------------------------
            if attach_files:
                for att in attach_files:  # attachments are tuples of (filepath, mimetype, filename)
                    with open(att[0], 'rb') as f:
                        content = f.read()
                    msg.attach(att[2], content, att[1])

            # Send email
            # --------------------------------

            msg.send(fail_silently=fail_silently)
        else:
            raise MailerInvalidBodyError('No text or html body supplied.')
889905
def _process_content_body(self, channel, payload):
        
        partial = self.partial_messages[channel]
        partial.add_payload(payload)
        if partial.complete:
            #
            # Stick the message in the queue and go back to
            # waiting for method frames
            #
            self.queue.put((channel, partial.method_sig, partial.args, partial.msg))
            del self.partial_messages[channel]
            self.expected_types[channel] = 1
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()
21253
def email(self, comment, content_object, request):
        
        if not self.email_notification:
            return

        send_comment_posted(comment, request)
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)
858847
async def _send_plain_text(self, request: Request, stack: Stack):
        

        await self._send_text(request, stack, None)
1188347
def send_msg(self, chat_id, msg_type, **kwargs):
        
        return self.send(chat_id, msg_type, **kwargs)