:param content_type: 如果 text 是html，则需要设置 _subtype='html'
        :param mail_to:
        :param subject:
        :param content:
        :param files: (f_name, f_data)
        :return:
977442
def send_email(self, mail_to, subject, content, content_type='plain', files=None):
        
        assert type(mail_to) == list
        server = self.smtp_server
        if files is None:
            files = []

        msg = MIMEMultipart()
        msg['From'] = self.mail_from
        msg['To'] = ', '.join(mail_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        # 如果 text 是html，则需要设置 _subtype='html'
        # 默认情况下 _subtype='plain'，即纯文本
        msg.attach(MIMEText(content, _subtype=content_type, _charset='utf-8'))

        for fn, fd in files:
            part = MIMEText(fd, 'base64', 'utf-8')
            part["Content-Type"] = 'application/octet-stream'
            basename = fn
            if PY2:
                basename = basename.encode('gb2312')
            # 文件名使用 gb2312 编码，否则会没有附件
            part.add_header('Content-Disposition', 'attachment', filename=('gb2312', '', basename))
            msg.attach(part)
        smtp = smtplib.SMTP(server, port=self.smtp_port)
        smtp.sendmail(self.mail_from, mail_to, msg.as_string())
        smtp.close()
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
644571
def _create_related_attachment(self, filename, content, mimetype=None):
        
        attachment = super(EmailMultiRelated, self)._create_attachment(filename, content, mimetype)
        if filename:
            mimetype = attachment['Content-Type']
            del(attachment['Content-Type'])
            del(attachment['Content-Disposition'])
            attachment.add_header('Content-Disposition', 'inline', filename=filename)
            attachment.add_header('Content-Type', mimetype, name=filename)
            attachment.add_header('Content-ID', '<%s>' % filename)
        return attachment
896172
def _message(self):
        """"""
        ascii_attachments = current_app.extensions['mail'].ascii_attachments
        encoding = self.charset or 'utf-8'

        attachments = self.attachments or []

        if len(attachments) == 0 and not self.alts:
            # No html content and zero attachments means plain text
            msg = self._mimetext(self.body, self.subtype)
        elif len(attachments) > 0 and not self.alts:
            # No html and at least one attachment means multipart
            subtype = self.subtype or 'mixed'
            msg = MIMEMultipart(_subtype=subtype)
            msg.attach(self._mimetext(self.body))
        else:
            # Anything else
            subtype = self.subtype or 'mixed'
            msg = MIMEMultipart(_subtype=subtype)
            alternative = MIMEMultipart(_subtype='alternative')
            alternative.attach(self._mimetext(self.body))
            for mimetype, content in self.alts.items():
                alternative.attach(self._mimetext(content, mimetype))
            msg.attach(alternative)

        if self.subject:
            msg['Subject'] = sanitize_subject(force_text(self.subject),
                                              encoding)

        msg['From'] = sanitize_address(self.sender, encoding)
        msg['To'] = ', '.join(
            list(set(sanitize_addresses(self.recipients, encoding)))
        )

        msg['Date'] = formatdate(self.date, localtime=True)
        # see RFC 5322 section 3.6.4.
        msg['Message-ID'] = self.msgId

        if self.cc:
            msg['Cc'] = ', '.join(
                list(set(sanitize_addresses(self.cc, encoding)))
            )

        if self.reply_to:
            msg['Reply-To'] = sanitize_address(self.reply_to, encoding)

        if self.extra_headers:
            for k, v in self.extra_headers.items():
                msg[k] = v

        SPACES = re.compile(r'[\s]+', re.UNICODE)
        for attachment in attachments:
            f = MIMEBase(*attachment.content_type.split('/'))
            f.set_payload(attachment.data)
            encode_base64(f)

            filename = attachment.filename
            if filename and ascii_attachments:
                # force filename to ascii
                filename = unicodedata.normalize('NFKD', filename)
                filename = filename.encode('ascii', 'ignore').decode('ascii')
                filename = SPACES.sub(u' ', filename).strip()

            try:
                filename and filename.encode('ascii')
            except UnicodeEncodeError:
                if not PY3:
                    filename = filename.encode('utf8')
                filename = ('UTF8', '', filename)

            f.add_header('Content-Disposition',
                         attachment.disposition,
                         filename=filename)

            for key, value in attachment.headers.items():
                f.add_header(key, value)

            if attachment.content_id:
                try:
                    f.replace_header('Content-ID', attachment.content_id)
                except KeyError:
                    f.add_header('Content-ID', attachment.content_id)

            msg.attach(f)
        if message_policy:
            msg.policy = message_policy

        return msg
359881
public function getMessage(array $to, $from_email, $from_name, $subject, $message_body, array $attachments, $mail_type='html')
    {
        $message = \Swift_Message::newInstance();
        $message->setTo($to);
        if ($attachments) {
            foreach ($attachments as $attachment) {
                foreach ($attachment as $file => $alt_name) {
                    if ($alt_name == '') {
                        $message->attach(\Swift_Attachment::fromPath($file));
                    } else {
                        $message->attach(\Swift_Attachment::fromPath($file)->setFilename($alt_name));
                    }
                }
            }
        }
        
        $message->setFrom($from_email, $from_name);
        $message->setSubject($subject);
        if ($mail_type == 'html') {
            $message->setBody($message_body, 'text/html');
        } else {
            $message->setBody($message_body);
        }
        
        return $message;
    }
1141781
public static void sendText(Collection<String> tos, String subject, String content, File... files) {
		send(tos, subject, content, false, files);
	}
139905
def content_type(path, filename)
      type = (filename.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
      case type
      when %r"jp(e|g|eg)"            then "image/jpeg"
      when %r"tiff?"                 then "image/tiff"
      when %r"png", "gif", "bmp"     then "image/#{type}"
      when "txt"                     then "text/plain"
      when %r"html?"                 then "text/html"
      when "js"                      then "application/js"
      when "csv", "xml", "css"       then "text/#{type}"
      else
        # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
        content_type = (`file -b --mime-type #{path}`.split(':').last.strip rescue "application/x-#{type}")
        content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/)
        content_type
      end
    end
38703
def email_template(rcpt, template_path, **kwargs):
    

    subject, content = parse_template(template_path, **kwargs)
    count = send_mail(subject, content, settings.DEFAULT_FROM_EMAIL,
                      [rcpt], fail_silently=True)
    return bool(count)
660493
function setContentType( $type = false, $charset = false,
                             $transferEncoding = false, $disposition = false, $boundary = false )
    {
        if ( $type )
        {
            $this->ContentType['type'] = $type;
        }
        if ( $charset )
            $this->ContentType['charset'] = $charset;
        if ( $transferEncoding )
            $this->ContentType['transfer-encoding'] = $transferEncoding;
        if ( $disposition )
            $this->ContentType['disposition'] = $disposition;
        if ( $boundary )
            $this->ContentType['boundary'] = $boundary;

        // if the body was already defined
        if ( $this->Mail->body instanceof ezcMailText )
        {
            // if the content-type is in the form of e.g. 'text/plain'
            if ( strpos( $this->ContentType['type'] ,'/' ) !== false )
            {
                list( $type, $subType ) = explode( '/', $this->ContentType['type'] );
                $this->Mail->body->subType = $subType;
            }
        }
    }
1205660
def attachment(filename=nil)
      response['Content-Disposition'] = 'attachment'
      if filename
        params = '; filename="%s"' % File.basename(filename)
        response['Content-Disposition'] << params
        ext = File.extname(filename)
        content_type(ext) unless response['Content-Type'] or ext.empty?
      end
    end
913792
def attachment(filename = nil, disposition = :attachment)
      response['Content-Disposition'] = disposition.to_s.dup
      if filename
        params = '; filename="%s"' % File.basename(filename)
        response['Content-Disposition'] << params
        ext = File.extname(filename)
        content_type(ext) unless response['Content-Type'] or ext.empty?
      end
    end
1157006
def parse_content_type(ct: str) -> Tuple[str, str, Mapping[str, str]]:
    
    pieces = ct.split(";")
    try:
        main_type, sub_type = pieces[0].split("/")
    except ValueError:
        msg = 'Invalid mime-type component: "{0}"'.format(pieces[0])
        raise ValueError(msg)
    if len(pieces) > 1:
        options = {}
        for opt in pieces[1:]:
            opt = opt.strip()
            if not opt:
                continue
            try:
                k, v = opt.split("=", 1)
            except ValueError:
                msg = 'Invalid option component: "{0}"'.format(opt)
                raise ValueError(msg)
            else:
                options[k.lower()] = v.lower()
    else:
        options = {}
    return main_type.lower(), sub_type.lower(), options
577951
def email(sender=None, receivers=(), cc=(), bcc=(),
          subject=None, content=None, encoding='utf8',
          attachments=()):
    
    enclosure = [HTML(content, encoding)]
    enclosure.extend(Attachment(k) for k in attachments)
    return Collection(
        *enclosure,
        headers=[
            headers.subject(subject),
            headers.sender(sender),
            headers.to(*receivers),
            headers.cc(*cc),
            headers.bcc(*bcc),
            headers.date(),
            headers.message_id(),
        ]
    )
516718
def get_content_type(name, content):
    
    if hasattr(content, "content_type"):
        content_type = content.content_type
    else:
        mime_type, encoding = mimetypes.guess_type(name)
        content_type = mime_type
    return content_type
1326575
def send(sender_instance):
    
    m = Mailin(
        "https://api.sendinblue.com/v2.0",
        sender_instance._kwargs.get("api_key")
    )
    data = {
        "to": email_list_to_email_dict(sender_instance._recipient_list),
        "cc": email_list_to_email_dict(sender_instance._cc),
        "bcc": email_list_to_email_dict(sender_instance._bcc),
        "from": email_address_to_list(sender_instance._from_email),
        "subject": sender_instance._subject,
    }
    if sender_instance._template.is_html:
        data.update({
            "html": sender_instance._message,
            "headers": {"Content-Type": "text/html; charset=utf-8"}
        })
    else:
        data.update({"text": sender_instance._message})
    if "attachments" in sender_instance._kwargs:
        data["attachment"] = {}
        for attachment in sender_instance._kwargs["attachments"]:
            data["attachment"][attachment[0]] = base64.b64encode(attachment[1])
    result = m.send_email(data)
    if result["code"] != "success":
        raise SendInBlueError(result["message"])
825529
def api_representation(self, content_type):
        
        payload = dict(Subject=self.subject, Body=dict(ContentType=content_type, Content=self.body))

        if self.sender is not None:
            payload.update(From=self.sender.api_representation())

        # A list of strings can also be provided for convenience. If provided, convert them into Contacts
        if any(isinstance(item, str) for item in self.to):
            self.to = [Contact(email=email) for email in self.to]

        # Turn each contact into the JSON needed for the Outlook API

        recipients = [contact.api_representation() for contact in self.to]

        payload.update(ToRecipients=recipients)

        # Conduct the same process for CC and BCC if needed
        if self.cc:
            if any(isinstance(email, str) for email in self.cc):
                self.cc = [Contact(email) for email in self.cc]

            cc_recipients = [contact.api_representation() for contact in self.cc]
            payload.update(CcRecipients=cc_recipients)

        if self.bcc:
            if any(isinstance(email, str) for email in self.bcc):
                self.bcc = [Contact(email) for email in self.bcc]

            bcc_recipients = [contact.api_representation() for contact in self.bcc]
            payload.update(BccRecipients=bcc_recipients)

        if self._attachments:
            payload.update(Attachments=[attachment.api_representation() for attachment in self._attachments])

        payload.update(Importance=str(self.importance))

        return dict(Message=payload)
1211494
def construct_message(self, email=None):
        
        # add subject, from and to
        self.multipart['Subject'] = self.subject
        self.multipart['From'] = self.config['EMAIL']
        self.multipart['Date'] = formatdate(localtime=True)
        if email is None and self.send_as_one:
            self.multipart['To'] = ", ".join(self.addresses)
        elif email is not None and self.send_as_one is False:
            self.multipart['To'] = email
        # add ccs
        if self.ccs is not None and self.ccs:
            self.multipart['Cc'] = ", ".join(self.ccs)
        # add html and text body
        html = MIMEText(self.html, 'html')
        alt_text = MIMEText(self.text, 'plain')
        self.multipart.attach(html)
        self.multipart.attach(alt_text)
        for file in self.files:
            self.multipart.attach(file)