当前位置: 首页>>代码示例>>Python>>正文


Python multipart.MIMEBase类代码示例

本文整理汇总了Python中email.mime.multipart.MIMEBase的典型用法代码示例。如果您正苦于以下问题:Python MIMEBase类的具体用法?Python MIMEBase怎么用?Python MIMEBase使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了MIMEBase类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: send_msg

    def send_msg(self, to, subject, body, attachments = None):
        if attachments:
            msg = MIMEMultipart()
            msg.attach(MIMEText( body))
        else:
            msg = MIMEText(body)
        msg['To']      = to
        msg['From']    = self.__username
        msg['Subject'] = subject
        if attachments:
            for path in attachments:
                if not os.path.exists(path):
                    break
 
                content_type, encoding = mimetypes.guess_type(path)
                if content_type is None or encoding is not None:
                    content_type = 'application/octet-stream'
 
                main_type, subtype = content_type.split('/', 1)
 
                with open(path, 'rb') as file:
                    data = file.read()
                    attachment = MIMEBase(main_type, subtype)
                    attachment.set_payload(data)
                    email.encoders.encode_base64(attachment)
 
                attachment.add_header('Content-Disposition', 'attachment',
                                       filename = os.path.basename(path))
                msg.attach(attachment)
 
        status = self.smtp.sendmail(self.__username, to, msg.as_string())
        return status
开发者ID:jinurhee,项目名称:scripts,代码行数:32,代码来源:pygmail.py

示例2: newMail

def newMail(mail_from, mail_to, mail_subj, mail_text, attach_list=[], mail_coding='utf-8'):
    """формирование сообщения"""
    multi_msg = MIMEMultipart()
    multi_msg['From'] = Header(mail_from, mail_coding)
    multi_msg['To'] = Header(mail_to, mail_coding)
    multi_msg['Subject'] =  Header(mail_subj, mail_coding)

    msg = MIMEText(mail_text.encode('utf-8'), 'plain', mail_coding)
    msg.set_charset(mail_coding)
    multi_msg.attach(msg)

    # присоединяем атач-файл
    for _file in attach_list:
        if exists(_file) and isfile(_file):
            with open(_file, 'rb') as fl:
                attachment = MIMEBase('application', "octet-stream")
                attachment.set_payload(fl.read())
                email.encoders.encode_base64(attachment)
                only_name_attach = Header(basename(_file), mail_coding)
                attachment.add_header('Content-Disposition',\
                    'attachment; filename="%s"' % only_name_attach)
                multi_msg.attach(attachment)
        else:
            if(attach_file.lstrip() != ""):
                print("Файл для атача не найден - %s" %_file)
    return multi_msg
开发者ID:yastrov,项目名称:py-tips,代码行数:26,代码来源:smtp.py

示例3: mail

def mail(mail_to, subject, text, file):
    """send email"""

    mailserver = smtplib.SMTP("smtp.gmail.com", 587)
    mailserver.starttls()
    mailserver.ehlo()
    mailserver.login(cred.get('GMAIL','USER'), cred['GMAIL']['PASSWD'])

    msg = MIMEMultipart()
    text_msg = MIMEText(text, "html")
    msg.attach(text_msg)
    contype = 'application/octet-stream'
    maintype, subtype = contype.split('/', 1)
    data = open(file, 'rb')
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(data.read())
    data.close()
    email.Encoders.encode_base64(file_msg)
    basename = os.path.basename(file)
    file_msg.add_header('Content-Disposition', 'attachment', filename=basename)
    msg.attach(file_msg)

    msg['Date'] = email.Utils.formatdate()
    msg['From'] = "[email protected]"
    msg['Subject'] = subject

    mailserver.sendmail(cred.get('GMAIL', 'USER'), mail_to, msg.as_string())
    mailserver.close()
开发者ID:hufengping,项目名称:percolata,代码行数:28,代码来源:Autotest.py

示例4: send_mail

def send_mail(from_user, pwd, to_user, cc_users, subject, text, attach):
        COMMASPACE = ", "
        msg = MIMEMultipart("alternative")
        #msg =  MIMEMultipart()
        msg["From"] = from_user
        msg["To"]   = to_user
        msg["Cc"] = COMMASPACE.join(cc_users)
        msg["Subject"] = Header(s=subject, charset="utf-8")
        msg["Date"] = Utils.formatdate(localtime = 1)
        msg.attach(MIMEText(text, "html", _charset="utf-8"))

        if (attach != None):
                part = MIMEBase("application", "octet-stream")
                part.set_payload(open(attach, "rb").read())
                Encoders.encode_base64(part)
                part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach))
                msg.attach(part)

        smtp_server  = "smtp.gmail.com"
        port         = 587

        smtp = smtplib.SMTP(smtp_server, port)
        smtp.starttls()
        smtp.login(from_user, pwd)
        print "gmail login OK!"
        smtp.sendmail(from_user, cc_users, msg.as_string())
        print "mail Send OK!"
        smtp.close()
开发者ID:dookim,项目名称:URQA-MessageBroker,代码行数:28,代码来源:mon.py

示例5: _send

def _send(subject, mail_from, rcpt_to, body, filename):

	root_message = MIMEMultipart()
	root_message["Subject"] = smtplib.email.Header.Header(subject, "utf-8")
	root_message["From"] = mail_from
	root_message["To"] = rcpt_to
	root_message["Date"] = formatdate()

	# 本文
	message = MIMEText(body)
	message.add_header("Content-Type", "text/plain; charset=UTF-8")
	root_message.attach(message)

	# 添付ファイル
	attachment = MIMEBase("text", "")
	attachment_body = _read_text_file(filename)
	attachment.set_payload(attachment_body)
	encoders.encode_base64(attachment)
	attachment.add_header("Content-Disposition", "attachment", filename=filename)
	root_message.attach(attachment)

	s = smtplib.SMTP("127.0.0.1:25")
	composed = root_message.as_string()
	s.sendmail(mail_from, [rcpt_to], composed)

	s.close()
开发者ID:mass10,项目名称:python.note,代码行数:26,代码来源:send-attachment.py

示例6: notificate

    def notificate(self, subject, message=None, files=None):
        """notificate.

        Args:
            subject:subject of email.
            message:message of email.
            files:file attacment.
        """
        # read to_addr  and to_name from notificate.ini
        config = readconfig()
        if not config:
            print('Not valid configure\n')
            return

        from_addr = config.from_addr
        from_name = config.from_name
        user = config.email_user
        password = config.email_password
        smtp_server = config.email_server
        smtp_port = config.email_port
        msg = MIMEMultipart()
        msg['From'] = _format_addr('%s <%s>' % (from_name, from_addr))
        msg['To'] = ', '.join([
            _format_addr('%s <%s>' % (to_name, to_addr))
            for to_addr, to_name in zip(config.addr, config.name)
        ])
        msg['Subject'] = Header(subject, 'utf-8').encode()
        if message:
            msg.attach(MIMEText('%s' % message, 'plain', 'utf-8'))
        if files:
            for filepath in files:
                with open(filepath, 'rb') as f:
                    part = MIMEBase('application', 'octet-stream')
                    part.add_header(
                        'Content-Disposition',
                        'attacment',
                        filename=os.path.basename(filepath))
                    part.set_payload(f.read())
                    encoders.encode_base64(part)
                    msg.attach(part)

        while True:
            try:
                server = smtplib.SMTP(smtp_server, smtp_port)
                server.starttls()
                server.login(user, password)
                server.sendmail(from_addr, config.addr, msg.as_string())
                server.quit()
                now = str(datetime.datetime.now().replace(second=0, microsecond=0))
                for to_addr in config.addr:
                    print('%s: Send email to %s successfully!\n' % (now, to_addr))
            except:
                raise
                time.sleep(300)
            else:
                break
开发者ID:Jin-Whu,项目名称:GNSSEvaluate,代码行数:56,代码来源:notificate.py

示例7: test_does_not_match_multipart_w_no_charset_not_utf8

 def test_does_not_match_multipart_w_no_charset_not_utf8(self):
     """
     Simulates mime messages created by stdlib email parser where  a part
     can have a charset set in the Content-Type header but get_charset()
     returns None.
     """
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     from email.mime.text import MIMEText
     body_text = u'Non \xe8 giusto costringermi ad usare il modulo email.'
     msg = MIMEMultipart()
     body = MIMEText(body_text.encode('ISO-8859-1'))
     body.set_charset(None)
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg), None)
开发者ID:marchon,项目名称:repoze.postoffice,代码行数:19,代码来源:test_filters.py

示例8: send_mail_with_file

def send_mail_with_file(content, args):
    r_content = '<html><body>' + u'<h1>嘿嘿哈哈</h1>'
    # message obj
    msg = MIMEMultipart()
    msg['From'] = _format_addr(u'小王 <%s>' % sender)
    msg['To'] = _format_addr(u'嘿嘿嘿 <%s>' % ','.join(receivers))
    msg['Subject'] = Header(u'老王准备嘿嘿嘿了', 'utf-8').encode()

 
    # add add_ons
    for idx, img in enumerate(args):
        try:
            with open('img/%s' % img, 'rb') as f:
                filename=str(idx)+'.jpg'
                # set MIME and filename
                # there is a keng
                mime = MIMEBase('image', 'jpg', filename=filename)
                # add header info 
                mime.add_header('Content-Disposition', 'attachment', filename=filename)
                mime.add_header('Content-ID', '<%s>' % idx)
                mime.add_header('X-Attachment-ID', str(idx))
                # add file content
                mime.set_payload(f.read())
                # base64 encode
                encoders.encode_base64(mime)
                # attach with msg
                msg.attach(mime)
                r_content += '<p><img src="cid:%s"></p>' % idx
        except:
            # raise
            continue

    # replace \n with <br /> in content
    # pattern = re.compile('\n')
    # content = re.sub(r'\n', '<br />\n    ', content)

    r_content = prefix + content + prefix + '</body></html>'
    # content text
    msg.attach(MIMEText(r_content, 'html', 'utf-8'))


    # send 
    server = smtplib.SMTP(smtp_server, 25)
    # server.set_debuglevel(1)
    server.login(sender, sender_password)
    server.sendmail(sender, receivers, msg.as_string())
    server.quit()
开发者ID:glrh111,项目名称:python-features,代码行数:47,代码来源:mail.py

示例9: prepare_attachment

 def prepare_attachment(self, path):
     filename = os.path.split(path)[1]
     bookname = filename.split('.')[0]
     booktype = filename.split('.')[1]
     with open(path, 'rb') as f:
         # 设置附件的MIME和文件名,这里是png类型:
         mime = MIMEBase(bookname, booktype, filename=filename)
         # 加上必要的头信息:
         mime.add_header('Content-Disposition', 'attachment', filename=filename)
         mime.add_header('Content-ID', '<0>')
         mime.add_header('X-Attachment-Id', '0')
         # 把附件的内容读进来:
         mime.set_payload(f.read())
         # 用Base64编码:
         encoders.encode_base64(mime)
         # 添加到MIMEMultipart:
         return mime
开发者ID:panthenia,项目名称:ebookpusher,代码行数:17,代码来源:BookPusher.py

示例10: test_matches_multipart_w_bogus_charset_in_content_type

 def test_matches_multipart_w_bogus_charset_in_content_type(self):
     """
     Simulates mime messages created by stdlib email parser where  a part
     can have a charset set in the Content-Type header but get_charset()
     returns None.
     """
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     from email.mime.text import MIMEText
     msg = MIMEMultipart()
     body = MIMEText('I am full of happy babies.  All days for Me!')
     body.set_charset(None)
     del body['Content-Type']
     body['Content-Type'] = 'text/plain; charset=bogus; flow=groovy'
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg),
                      "body_regexp: body matches u'happy.+days'")
开发者ID:marchon,项目名称:repoze.postoffice,代码行数:21,代码来源:test_filters.py

示例11: create_message

def create_message(path):
    "Return a Message object with the file at path attached"
    d, fname = os.path.split(path)

    # create the outer message
    msg = MIMEMultipart()
    msg['From'] = email.utils.formataddr((OPTIONS['name'], OPTIONS['email']))
    
    fname_parts = fname.split('::')
    if len(fname_parts) == 2:
        to_addr, att_name = fname_parts[0], fname_parts[1]
    else:
        raise FeedbackError("Bad filename: %s; can't determine recipient or attachment name" %
                            fname)

    msg['To'] = to_addr
    msg['Subject'] = OPTIONS['feedback_subject']

    # first part: the text/plain message derived from FEEDBACK_MSG
    body = MIMEText(FEEDBACK_MSG % {'signature' : OPTIONS['name']})
    msg.attach(body)

    # second part: attachment 
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    
    f = open(path, 'rb')

    att = MIMEBase(maintype, subtype)
    att.set_payload(f.read())
    email.encoders.encode_base64(att)
    att.add_header('Content-Disposition', 'attachment', filename=att_name)
    msg.attach(att)

    logging.info("Created feedback message for %s from file %s" % (to_addr, path))

    return msg
开发者ID:marchon,项目名称:student_email_submit,代码行数:39,代码来源:email_submit.py

示例12: send

    def send(self, to, subject, message, attachments=None):
        """
        Send an email. May also include attachments.

        to          -- The email recipient.
        subject     -- The email subject.
        message     -- The email body.
        attachments -- A list of file names to include.
        """
        if attachments is None:
            attachments = []
        msg = MIMEMultipart()
        msg.attach(MIMEText(message))
        for path in attachments:
            content_type, encoding = mimetypes.guess_type(path)
            if content_type is None or encoding is not None:
                content_type = 'application/octet-stream'

            main_type, subtype = content_type.split('/', 1)

            with open(path, 'rb') as file:
                data = file.read()
                attachment = MIMEBase(main_type, subtype)
                attachment.set_payload(data)
                email.encoders.encode_base64(attachment)

            attachment.add_header('Content-Disposition',
                                  'attachment',
                                  filename=os.path.basename(path))
            msg.attach(attachment)

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

        log.debug('GMAIL: Sending email to %s' % msg['To'])
        errors = self.smtp.sendmail(self.__username, to, msg.as_string())

        return msg, errors
开发者ID:legastero,项目名称:Weld,代码行数:39,代码来源:gmail.py

示例13: test_matches_multipart_w_comment_in_charset

    def test_matches_multipart_w_comment_in_charset(self):
        """
        At least one email client out there generates content type headers that
        look like::

            Content-Type: text/html; charset="utf-8" //iso-8859-2
        """
        from email.mime.multipart import MIMEMultipart
        from email.mime.multipart import MIMEBase
        from email.mime.text import MIMEText
        msg = MIMEMultipart()
        body = MIMEText('I am full of happy babies.  All days for Me!')
        body.set_charset(None)
        del body['Content-Type']
        body['Content-Type'] = 'text/plain; charset="utf-8" //iso-8859-2'
        msg.attach(body)
        other = MIMEBase('application', 'pdf')
        other.set_payload('Not really a pdf.')
        msg.attach(other)
        fut = self._make_one()
        self.assertEqual(fut(msg),
                         "body_regexp: body matches u'happy.+days'")
开发者ID:marchon,项目名称:repoze.postoffice,代码行数:22,代码来源:test_filters.py

示例14: attachments

    def attachments(self):
        folder = self._attachments_folder
        if folder is None:
            return [], [], {}

        profile = self.profile
        request = self.request
        attachments = []
        attachment_links = []
        attachment_hrefs = {}
        for name, model in folder.items():
            if profile.alert_attachments == 'link':
                attachment_links.append(name)
                attachment_hrefs[name] = resource_url(model, request)

            elif profile.alert_attachments == 'attach':
                with model.blobfile.open() as f:
                    f.seek(0, 2)
                    size = f.tell()
                    if size > MAX_ATTACHMENT_SIZE:
                        attachment_links.append(name)
                        attachment_hrefs[name] = resource_url(model, request)

                    else:
                        f.seek(0, 0)
                        data = f.read()
                        type, subtype = model.mimetype.split('/', 1)
                        attachment = MIMEBase(type, subtype)
                        attachment.set_payload(data)
                        Encoders.encode_base64(attachment)
                        attachment.add_header(
                            'Content-Disposition',
                            'attachment; filename="%s"' % model.filename)
                        attachments.append(attachment)

        return attachments, attachment_links, attachment_hrefs
开发者ID:Falmarri,项目名称:karl,代码行数:36,代码来源:adapters.py

示例15: test_does_not_multipart

 def test_does_not_multipart(self):
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     msg = MIMEMultipart()
     body = MIMEBase('x-application', 'not-text')
     body.set_payload('I am full of happy babies.  All Days for Me!')
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg), None)
开发者ID:marchon,项目名称:repoze.postoffice,代码行数:12,代码来源:test_filters.py


注:本文中的email.mime.multipart.MIMEBase类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。