Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content.
    Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md
976889
def build_attachment1():
    """"""
    attachment = Attachment()
    attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl"
                          "Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12")
    attachment.type = "application/pdf"
    attachment.filename = "balance_001.pdf"
    attachment.disposition = "attachment"
    attachment.content_id = "Balance Sheet"
    return attachment
843992
def put_attachment(self, attachmentid, attachment_update):
        ''''''
        assert type(attachment_update) is DotDict
        if (not 'ids' in attachment_update):
            attachment_update.ids = [attachmentid]

        return self._put('bug/attachment/{attachmentid}'.format(attachmentid=attachmentid),
                json.dumps(attachment_update))
508932
def create_git_blob(self, content, encoding):
        
        assert isinstance(content, (str, unicode)), content
        assert isinstance(encoding, (str, unicode)), encoding
        post_parameters = {
            "content": content,
            "encoding": encoding,
        }
        headers, data = self._requester.requestJsonAndCheck(
            "POST",
            self.url + "/git/blobs",
            input=post_parameters
        )
        return github.GitBlob.GitBlob(self._requester, headers, data, completed=True)
954412
def build_attachment(self, text, target, attachment, thread):
        '''
        '''

        attachment = {
            'as_user': True,
            'text': text,
            'channel': target,
            'attachments': [
                {
                    'fallback': text,
                    'image_url': attachment
                }
            ]
        }
        if thread:
            attachment['thread_ts'] = thread
        return attachment
867219
function getAttachment(binaryKey) {
    // console.log('Adding binary attachment', binaryKey);
    const index = attachments.findIndex((att) => (att.key === binaryKey));
    if (index !== -1) {
      const result = attachments[index].data;
      // TODO if attachment is sent mulitple times, we shouldn't remove it yet.
      attachments.splice(index, 1);
      return result;
    }
    console.error('Binary attachment key found without matching attachment');
    return null;
  }
368500
def as_file(self):
        """"""
        use_data_if_no_file = not self._file and self._data
        if use_data_if_no_file:
            if self._base64_file_content:
                if isinstance(self._data, str):
                    content = self._data.encode()
                else:
                    content = self._data
                self._file = _create_temp_file_with_content(
                    base64.standard_b64decode(content))
            else:
                self._file = _create_temp_file_with_content(self._data)
        if self._file and not os.path.isfile(self._file):
            raise ConfigException("File does not exists: %s" % self._file)
        return self._file
1272831
def dump_to_response(request, app_label=None, exclude=None,
                     filename_prefix=None):
    
    app_label = app_label or []
    exclude = exclude
    try:
        filename = '%s.%s' % (datetime.now().isoformat(),
                              settings.SMUGGLER_FORMAT)
        if filename_prefix:
            filename = '%s_%s' % (filename_prefix, filename)
        if not isinstance(app_label, list):
            app_label = [app_label]
        response = serialize_to_response(app_label, exclude)
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response
    except CommandError as e:
        messages.error(
            request,
            _('An exception occurred while dumping data: %s') % force_text(e))
    return HttpResponseRedirect(request.build_absolute_uri().split('dump')[0])
1078383
def parse_template(self, tmp, reset=False, only_body=False):
        
        logging.debug('GoT: """\n%s\n"""', tmp)

        if self.sent_time:
            self.modified_since_sent = True

        if only_body:
            self.body = tmp
        else:
            m = re.match(r'(?P<h>([a-zA-Z0-9_-]+:.+\n)*)\n?(?P<b>(\s*.*)*)',
                         tmp)
            assert m

            d = m.groupdict()
            headertext = d['h']
            self.body = d['b']

            # remove existing content
            if reset:
                self.headers = {}

            # go through multiline, utf-8 encoded headers
            # we decode the edited text ourselves here as
            # email.message_from_file can't deal with raw utf8 header values
            key = value = None
            for line in headertext.splitlines():
                if re.match('[a-zA-Z0-9_-]+:', line):  # new k/v pair
                    if key and value:  # save old one from stack
                        self.add(key, value)  # save
                    key, value = line.strip().split(':', 1)  # parse new pair
                    # strip spaces, otherwise we end up having " foo" as value
                    # of "Subject: foo"
                    value = value.strip()
                elif key and value:  # append new line without key prefix
                    value += line
            if key and value:  # save last one if present
                self.add(key, value)

            # interpret 'Attach' pseudo header
            if 'Attach' in self:
                to_attach = []
                for line in self.get_all('Attach'):
                    gpath = os.path.expanduser(line.strip())
                    to_attach += [g for g in glob.glob(gpath)
                                  if os.path.isfile(g)]
                logging.debug('Attaching: %s', to_attach)
                for path in to_attach:
                    self.attach(path)
                del self['Attach']
854287
def file_body(message, file)
      file_name = File.basename(file.path)
      mime_type = MimeMagic.by_path(file_name)
      file_content = Base64.encode64(file.read)

      body =  ["--#{BOUNDARY}"]
      body << 'Content-Type: application/json; charset=UTF-8'
      body << 'Content-Disposition: attachment; name="metadata"'
      body << ''
      body << message
      body << "--#{BOUNDARY}"
      body << "Content-Type: #{mime_type}; charset=UTF-8"
      body << 'Content-Transfer-Encoding: base64'
      body << %{Content-Disposition: attachment; name="file"; filename="#{file_name}"}
      body << ''
      body << file_content
      body << "--#{BOUNDARY}--"
      body.join("\n")
    end
273408
async def send_with_attachments(subject, message, filepaths, config):
    
    email_ = MIMEMultipart()
    email_.attach(MIMEText(message))
    email_["Subject"] = subject
    email_["From"] = get_attribute_from_config(config, EMAIL_SECTION_KEY, USER_KEY)
    email_["To"] = get_attribute_from_config(config, EMAIL_SECTION_KEY, RECEIVER_KEY)
    _attach_files(filepaths, email_)
    await _send_email(email_, config)
345653
public static MimeBodyPart newAttachmentBodyPart( String content, String contentId, String mimeType, String fileName)
    throws MessagingException, IOException
  {
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
//    log.debug("Creating an attachment for content '{}', mimeType '{}', fileName '{}'.", new Object[] {content, mimeType, fileName});
    mimeBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(content, mimeType + UTF_8_CHARACTER_SET)));
    if( contentId != null ) {
      mimeBodyPart.setHeader("Content-ID", contentId);
    }
    mimeBodyPart.setDisposition(DISPOSITION_ATTACHMENT);
    if( fileName != null ) {
      mimeBodyPart.setFileName(fileName);
    }
    return mimeBodyPart;
  }
304219
function buildData(context) {

    if (/^Head|Get|Delete$/.test( context.method ))  return '';

    const request = context.request;

    if (request.type !== 'multipart/form-data')  return request.body;

    const form = new FormData();

    for (let key in request.fields)  form.append(key, request.fields[ key ]);

    for (let key in request.files)
        request.files[ key ].forEach(file =>
            form.append(key,  createReadStream( file.path ),  file.name)
        );

    return form;
}
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
1218682
def add_attachment(self, file_path, mimetype=None):
        """"""
        if not mimetype:
            mimetype, _ = mimetypes.guess_type(file_path)

        if mimetype is None:
            mimetype = 'application/octet-stream'

        type_maj, type_min = mimetype.split('/')
        with open(file_path, 'rb') as fh:
            part_data = fh.read()

            part = MIMEBase(type_maj, type_min)
            part.set_payload(part_data)
            email_encoders.encode_base64(part)

            part_filename = os.path.basename(self._encoded(file_path))
            part.add_header('Content-Disposition', 'attachment; filename="%s"'
                            % part_filename)

            self._parts.append((mimetype, part))
71281
def encode_multipart_formdata(self, fields, files, baseName, verbose=False):
        
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        if verbose is True:
            print(('Encoding ' + baseName + ' for upload...'))
        fin = self._open(files, 'rb')
        fout = self._open(files + '.b64', 'wb')
        fout.write(bytearray('--' + BOUNDARY + CRLF, 'utf-8'))
        fout.write(bytearray('Content-Disposition: form-data'
                             '; name="file"; filename="' + baseName + '"' + CRLF, "utf-8"))
        fout.write(bytearray('Content-Type: application/octet-stream' + CRLF,
                             'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        shutil.copyfileobj(fin, fout)
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.write(bytearray('--' + BOUNDARY + '--' + CRLF, 'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.close()
        fin.close()
        return content_type
970595
def upload_attachment(self, location, data):
        
        self.validate_attachment_location(location)
        content = data.read() if hasattr(data, 'read') else data
        orig_content = content
        if isinstance(content, bytes):
            content = base64.b64encode(orig_content).decode('ascii')
        else:
            pass  # Should be base64 encoded already
        apath = '%s/%s' % (self.attachment_location, location)
        url = '%s/contents/%s' % (self.base_url, apath)
        result = requests.put(
            url, auth=(self.user, self.token), data=json.dumps({
                'message': 'file attachment %s' % location,
                'content': content}))
        if result.status_code != 201:
            raise ValueError(
                "Can't upload attachment %s due to error %s." % (
                    location, result.reason))
        return '[%s](https://github.com/%s/%s/blob/master/%s)' % (
            location, self.owner, self.realm, apath)
1349478
def file_to_attachment(filename, filehandler=None):
    
    if filehandler:
        return {'_name': filename,
                'content': base64.b64encode(filehandler.read())
        }
    with open(filename, 'rb') as _file:
        return {'_name': filename,
                'content': base64.b64encode(_file.read())
        }