Create an email message object which implements the
    email.message.Message interface and which has the files to be shared
    attached to it.
422187
def create_email(filepaths, collection_name):
    
    outer = MIMEMultipart()
    outer.preamble = 'Here are some files for you'

    def add_file_to_outer(path):
        if not os.path.isfile(path):
            return

        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)

        if maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'text':
            # We do this to catch cases where text files have
            # an encoding we can't guess correctly.
            try:
                fp = open(path, 'r')
                msg = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            except UnicodeDecodeError:
                fp = open(path, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                encoders.encode_base64(msg)
                fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment',
                filename=os.path.basename(path))
        outer.attach(msg)

    outer.attach(MIMEText("Here are some files I've thrown at you."))
    
    for path in filepaths:
        add_file_to_outer(path)

    return outer
1190412
def from_EmailMessage(cls, message):
        
        mail = cls(
            from_email=Email(message.get('From')),
            subject=message.get('Subject'),
            to_emails=Email(message.get('To')),
        )
        try:
            body = message.get_content()
        except AttributeError:
            # Python2
            body = message.get_payload()
        mail.add_content(Content(
            message.get_content_type(),
            body.strip()
        ))
        for k, v in message.items():
            mail.add_header(Header(k, v))
        return mail
824400
def send_message(message, pipe='public'):
    
    if pipe not in ['public', 'private']:
        raise ValueError('pipe argument can be only "public" or "private"')
    else:
        pipe = pipe.upper()

    pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' else PRIVATE_PIPE

    # create file if it doesn't exist, append contents
    pipeout = open(pipe_path, 'a')

    pipeout.write('%s\n' % message)
    pipeout.close()
887977
def save_model(self, request, obj, form, change):
        
        email = message.EmailMessage(
            subject=obj.subject,
            body=obj.body,
            from_email=obj.from_email,
            to=[t.strip() for t in obj.to_emails.split(',')],
            bcc=[t.strip() for t in obj.bcc_emails.split(',')],
            cc=[t.strip() for t in obj.cc_emails.split(',')]
        )
        email.send()
887441
def _build_message(self, to, text, subject=None, mtype=None, unsubscribe_url=None):
        """"""
        # TODO Maybe file attachments handling through `files` message_model context var.

        if subject is None:
            subject = u'%s' % _('No Subject')

        if mtype == 'html':
            msg = self.mime_multipart()
            text_part = self.mime_multipart('alternative')
            text_part.attach(self.mime_text(strip_tags(text), _charset='utf-8'))
            text_part.attach(self.mime_text(text, 'html', _charset='utf-8'))
            msg.attach(text_part)

        else:
            msg = self.mime_text(text, _charset='utf-8')

        msg['From'] = self.from_email
        msg['To'] = to
        msg['Subject'] = subject

        if unsubscribe_url:
            msg['List-Unsubscribe'] = '<%s>' % unsubscribe_url

        return msg
652623
def add_message(self, msg_content, folder, **kwargs):
        
        content = {'m': kwargs}
        content['m']['l'] = str(folder)
        content['m']['content'] = {'_content': msg_content}

        return self.request('AddMsg', content)
149384
def folder_created_message(self, request, folder):
        
        messages.success(request, _("Folder {} was created".format(folder)))
1345672
def _send_message(session, user_id, message=None, image_files=None):
        
        assert any([message, image_files])

        attachment_items = None
        if image_files:
            attachment_items = Photo._upload_messages_photos_for_group(session, user_id, image_files)

        message_id = session.fetch("messages.send", user_id=user_id, message=message, attachment=attachment_items, random_id=random.randint(1, 10**6))
        return message_id
1302852
def create_email(self):
        
        self.connect()
        if self.send_as_one:
            self.construct_message()
            self.send()
        elif self.send_as_one is False:
            for email in self.addresses:
                self.construct_message(email)
                self.send(email)
        self.disconnect()
150347
def attach(self, filename, filetype="txt"):
		
		shutit = self.shutit
		host_path = '/tmp'
		host_fn = shutit.get_file(filename, host_path)
		if self.config['shutit.core.alerting.emailer.compress']:
			filetype = 'x-gzip-compressed'
			filename = self.__gzip(host_fn)
			host_fn = os.path.join(host_path, os.path.basename(filename))
		file_pointer = open(host_fn, 'rb')
		attach = MIMEApplication(file_pointer.read(), _subtype=filetype)
		file_pointer.close()
		attach.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename))
		self.attaches.append(attach)
981301
private void createAckMailboxesIfNeeded(final Set<Integer> localPartitions) {
        m_mailboxesZKPath = VoltZK.exportGenerations + "/" + "mailboxes";
        if (m_mbox == null) {
            m_mbox = new LocalMailbox(m_messenger) {
                @Override
                public void deliver(VoltMessage message) {
                    if (message instanceof BinaryPayloadMessage) {
                        BinaryPayloadMessage bpm = (BinaryPayloadMessage)message;
                        ByteBuffer buf = ByteBuffer.wrap(bpm.m_payload);
                        final byte msgType = buf.get();
                        final int partition = buf.getInt();
                        final Map<String, ExportDataSource> partitionSources = m_dataSourcesByPartition.get(partition);

                        final int length = buf.getInt();
                        byte stringBytes[] = new byte[length];
                        buf.get(stringBytes);
                        String tableName = new String(stringBytes, Constants.UTF8ENCODING);
                        if (partitionSources == null) {
                            if (!m_removingPartitions.contains(partition)) {
                                exportLog.error("Received an export message " + msgType + " for partition " + partition +
                                        " which does not exist on this node");
                            }
                            return;
                        }
                        final ExportDataSource eds = partitionSources.get(tableName);
                        if (eds == null) {
                            // For dangling buffers
                            if (msgType == ExportManager.TAKE_MASTERSHIP) {
                                final long requestId = buf.getLong();
                                if (exportLog.isDebugEnabled()) {
                                    exportLog.debug("Received TAKE_MASTERSHIP message(" + requestId +
                                            ") for a stream that no longer exists from " +
                                            CoreUtils.hsIdToString(message.m_sourceHSId) +
                                            " to " + CoreUtils.hsIdToString(m_mbox.getHSId()));
                                }
                                sendDummyTakeMastershipResponse(message.m_sourceHSId, requestId, partition, stringBytes);
                            } else {
                                exportLog.warn("Received export message " + msgType + " for partition " +
                                        partition + " source " + tableName +
                                        " which does not exist on this node, sources = " + partitionSources);
                            }
                            return;
                        }

                        if (msgType == ExportManager.RELEASE_BUFFER) {
                            final long seqNo = buf.getLong();
                            final long catalogVersion = buf.getInt();
                            try {
                                if (exportLog.isDebugEnabled()) {
                                    exportLog.debug("Received RELEASE_BUFFER message for " + eds.toString() +
                                            " , sequence number: " + seqNo + ", catalogVersion: " + catalogVersion +
                                            " from " + CoreUtils.hsIdToString(message.m_sourceHSId) +
                                            " to " + CoreUtils.hsIdToString(m_mbox.getHSId()));
                                }
                                eds.remoteAck(seqNo);
                            } catch (RejectedExecutionException ignoreIt) {
                                // ignore it: as it is already shutdown
                            }
                        } else if (msgType == ExportManager.GIVE_MASTERSHIP) {
                            final long ackSeqNo = buf.getLong();
                            try {
                                if (exportLog.isDebugEnabled()) {
                                    exportLog.debug("Received GIVE_MASTERSHIP message for " + eds.toString() +
                                            " with sequence number:" + ackSeqNo +
                                            " from " + CoreUtils.hsIdToString(message.m_sourceHSId) +
                                            " to " + CoreUtils.hsIdToString(m_mbox.getHSId()));
                                }
                                eds.remoteAck(ackSeqNo);
                            } catch (RejectedExecutionException ignoreIt) {
                                // ignore it: as it is already shutdown
                            }
                            eds.acceptMastership();
                        } else if (msgType == ExportManager.GAP_QUERY) {
                            final long requestId = buf.getLong();
                            long gapStart = buf.getLong();
                            if (exportLog.isDebugEnabled()) {
                                exportLog.debug("Received GAP_QUERY message(" + requestId +
                                        ") for " + eds.toString() +
                                        " from " + CoreUtils.hsIdToString(message.m_sourceHSId) +
                                        " to " + CoreUtils.hsIdToString(m_mbox.getHSId()));
                            }
                            eds.handleQueryMessage(message.m_sourceHSId, requestId, gapStart);
                        } else if (msgType == ExportManager.QUERY_RESPONSE) {
                            final long requestId = buf.getLong();
                            final long lastSeq = buf.getLong();
                            if (exportLog.isDebugEnabled()) {
                                exportLog.debug("Received QUERY_RESPONSE message(" + requestId +
                                        "," + lastSeq + ") for " + eds.toString() +
                                        " from " + CoreUtils.hsIdToString(message.m_sourceHSId) +
                                        " to " + CoreUtils.hsIdToString(m_mbox.getHSId()));
                            }
                            eds.handleQueryResponse(message.m_sourceHSId, requestId, lastSeq);
                        } else if (msgType == ExportManager.TAKE_MASTERSHIP) {
                            final long requestId = buf.getLong();
                            if (exportLog.isDebugEnabled()) {
                                exportLog.debug("Received TAKE_MASTERSHIP message(" + requestId +
                                        ") for " + eds.toString() +
                                        " from " + CoreUtils.hsIdToString(message.m_sourceHSId) +
                                        " to " + CoreUtils.hsIdToString(m_mbox.getHSId()));
                            }
                            eds.handleTakeMastershipMessage(message.m_sourceHSId, requestId);
                        } else if (msgType == ExportManager.TAKE_MASTERSHIP_RESPONSE) {
                            final long requestId = buf.getLong();
                            if (exportLog.isDebugEnabled()) {
                                exportLog.debug("Received TAKE_MASTERSHIP_RESPONSE message(" + requestId +
                                        ") for " + eds.toString() +
                                        " from " + CoreUtils.hsIdToString(message.m_sourceHSId) +
                                        " to " + CoreUtils.hsIdToString(m_mbox.getHSId()));
                            }
                            eds.handleTakeMastershipResponse(message.m_sourceHSId, requestId);
                        } else {
                            exportLog.error("Receive unsupported message type " + message + " in export subsystem");
                        }
                    } else {
                        exportLog.error("Receive unexpected message " + message + " in export subsystem");
                    }
                }
            };
            m_messenger.createMailbox(null, m_mbox);
        }

        // Rejoining node may receives gap query message before childUpdating thread gets back result,
        // in case it couldn't find local mailbox to send back response, add local mailbox to the list first.
        for (Integer partition : localPartitions) {
            updateAckMailboxes(partition, null);
        }
        // Update latest replica list to each data source.
        updateReplicaList(localPartitions);
    }
498550
def send_message(template_id, to, reply_to, from, subject, merge_fields = nil, view_online = false,
                                            click_tracking = true, suppress_address = false, attachments = nil, headers = nil)
      if attachments
          upload(template_id, to, reply_to, from, subject, merge_fields, view_online, click_tracking,
                                                                                    suppress_address, attachments, headers, nil, nil)
        else
          post @endpoint, params = {template_id: template_id, to: to, reply_to: reply_to, from: from,
                                    subject: subject, merge_fields: merge_fields, view_online: view_online,
                                    click_tracking: click_tracking, suppress_address: suppress_address, headers: headers}
      end
    end
159221
def _send(self, server, texts, htmls, dryrun):
        
        import smtplib
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText

        # Create message container - the correct MIME type is multipart/alternative.
        emsg = MIMEMultipart('alternative')
        emsg['Subject'] = self.subject
        emsg['From'] = self.sender
        emsg['To'] = ', '.join(self.to)

        # Create the body of the message (a plain-text and an HTML version).
        self.text = '\n'.join(texts) if isinstance(texts, list) else texts
        self.html = """
        <html>
          <head></head>
          <body>
            {}  
          </body>
        </html>
        """.format('\n'.join(htmls) if isinstance(htmls, list) else htmls)

        # Record the MIME types of both parts - text/plain and text/html.
        part1 = MIMEText(self.text, 'plain')
        part2 = MIMEText(self.html, 'html')

        # Attach parts into message container.
        # According to RFC 2046, the last part of a multipart message, in this case
        # the HTML message, is best and preferred.
        emsg.attach(part1)
        emsg.attach(part2)

        # Send the message via the configured SMTP server from ANCLE global configuration.
        if not dryrun:
            s = smtplib.SMTP(server.settings.gateway)
            s.sendmail(self.sender, self.to, emsg.as_string())
            s.quit()

        self.sent = True
465110
def to_email_attachment(self, filename, filedata, **kw):
        
        maintype = "application"
        subtype = "octet-stream"

        mime_type = mimetypes.guess_type(filename)[0]
        if mime_type is not None:
            maintype, subtype = mime_type.split("/")

        attachment = MIMEBase(maintype, subtype, **kw)
        attachment.set_payload(filedata)
        encoders.encode_base64(attachment)
        attachment.add_header("Content-Disposition",
                              "attachment; filename=%s" % filename)
        return attachment
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)
773490
def create(self, msgtype, *args, **kwargs):
        ''' 

        '''
        if msgtype not in self._messages:
            raise ProtocolError("Unknown message type %r for protocol version %s" % (msgtype, self._version))
        return self._messages[msgtype].create(*args, **kwargs)
890776
def send_file_message(self, filename):
        """"""
        data = self._readFile(filename)
        self.print_debug_message(data)
        self.socket.send(data)