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


Python EmailMessage.as_string方法代码示例

本文整理汇总了Python中email.message.EmailMessage.as_string方法的典型用法代码示例。如果您正苦于以下问题:Python EmailMessage.as_string方法的具体用法?Python EmailMessage.as_string怎么用?Python EmailMessage.as_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在email.message.EmailMessage的用法示例。


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

示例1: deliver_email

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import as_string [as 别名]

#.........这里部分代码省略.........
                self.logger.debug('found key: {}'.format(rk))
                media = media_urls.get(rk)
                if not media:
                    media = media_urls['UNKNOWN']
                media = 'https://southmeriden-vfd.org/images/dispatchbuddy/icon-'+media
                medias.append(media)

        medias = set(medias)

        self.logger.debug('media urls: {}'.format(medias))

        meta_icons_t = ''
        if medias:
            meta_icons_t = ''
            for url in medias:
                meta_icons_t += '<img class="meta_icons" src="{url}">'.format(url=url)

        fdict.update({'meta_icons':meta_icons_t})

        for kw in ('meta_icons', 'magnify_icon_cid'):
            msgbody = msgbody.replace('{{'+kw+'}}','{'+kw+'}')

        msgbody = msgbody.format(**fdict)

        # now replace all the {{ and }}
        msgbody = msgbody.replace('{{','{').replace('}}','}')

        msg.add_alternative(msgbody, subtype='html')

        with open('/var/bluelabs/DispatchBuddy/images/magnify.gif', 'rb') as img:
            msg.get_payload()[1].add_related(img.read(), 'image', 'gif', cid=magnify_icon_cid)

        '''
        related = MIMEMultipart(_subtype='related')
        innerhtml = MIMEText(msgbody, _subtype='html')
        related.attach(innerhtml)
        related.attach(icon_magnify_gif)
        '''

        for h,v in urgheaders:
            msg[h]=v

        bcc = [r.address for r in rx]

        '''
            medias = []
            if self.mediatype == 'mms':
                for rk in sorted(media_urls):
                    if re.search(rk, self.evdict['nature']) or re.search(rk, self.evdict['notes']):
                        media = media_urls.get(rk)
                        if not media:
                            media = media_urls['UNKNOWN']
                        media = 'https://southmeriden-vfd.org/images/dispatchbuddy/'+media

                args['media_url'] = medias

            print('args list: {}'.format(args))
        '''

        host  = self.config.get('SMTP', 'host')
        ehlo  = self.config.get('SMTP', 'ehlo')
        user  = self.config.get('SMTP', 'user')
        pass_ = self.config.get('SMTP', 'pass')
        from_ = self.config.get('SMTP', 'from')

        try:
            s = smtplib.SMTP(host=host, port='25')
            #s.set_debuglevel(1)
            s.starttls()
            s.ehlo(ehlo)
            s.login(user, pass_)
            # keep_results is my own patch to smtplib
            try:
                sresponse = s.sendmail(from_, bcc, msg.as_string(), mail_options=['SMTPUTF8'], keep_results=True)
            except TypeError:
                self.logger.critical('Need to patch smtplib for keep_results again; https://bugs.python.org/issue29539')
                sresponse = s.sendmail(from_, bcc, msg.as_string(), mail_options=['SMTPUTF8'])
            qresponse = s.quit()
            self.logger.debug('server sresponse: {}'.format(sresponse))
            self.logger.debug('server qresponse: {}'.format(qresponse))

            for r in bcc:
                code,status = sresponse[r]
                status      = status.decode().split()
                id          = status[4]
                status      = status[2]

                try:
                    status_recorder(recipient=r, delivery_id=id, status=status)
                except Exception as e:
                    self.logger.warning('unable to relay status elements to DB recorder: {}'.format(e))
                    status_recorder(recipient=r, delivery_id=id, status='failed', reason=str(e), completed=True)

        except Exception as e:
            self.logger.warning('Failed to send message to recipients: {}'.format(e))
            for r in bcc:
                try:
                    status_recorder(recipient=r, delivery_id='smtp failure', status='failed', reason=str(e), completed=True)
                except Exception as ee:
                    self.logger.warning('status recording error: {}'.format(ee))
开发者ID:Blue-Labs,项目名称:DispatchBuddy,代码行数:104,代码来源:gateways.py

示例2: encrypt

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import as_string [as 别名]
def encrypt(message, certs, algorithm='aes256_cbc'):
    """
    Takes the contents of the message parameter, formatted as in RFC 2822 (type str or message), and encrypts them,
    so that they can only be read by the intended recipient specified by pubkey.
    :return: the new encrypted message (type str or message, as per input).
    """
    # Get the chosen block cipher
    block_cipher = get_cipher(algorithm)
    if block_cipher == None:
        raise ValueError('Unknown block algorithm')

    # Get the message content. This could be a string, or a message object
    passed_as_str = isinstance(message, str)
    if passed_as_str:
        msg = message_from_string(message)
    else:
        msg = message
    # Extract the message payload without conversion, & the outermost MIME header / Content headers. This allows
    # the MIME content to be rendered for any outermost MIME type incl. multipart
    pl = EmailMessage()
    for i in msg.items():
        hname = i[0].lower()
        if hname == 'mime-version' or hname.startswith('content-'):
            pl.add_header(i[0], i[1])
    pl._payload = msg._payload
    content = pl.as_string()

    recipient_infos = []
    for recipient_info in __iterate_recipient_infos(certs, block_cipher.session_key):
        if recipient_info == None:
            raise ValueError('Unknown public-key algorithm')
        recipient_infos.append(recipient_info)

    # Encode the content
    encrypted_content_info = block_cipher.encrypt(content)

    # Build the enveloped data and encode in base64
    enveloped_data = cms.ContentInfo({
        'content_type': 'enveloped_data',
        'content': {
            'version': 'v0',
            'recipient_infos': recipient_infos,
            'encrypted_content_info': encrypted_content_info
        }
    })
    encoded_content = '\n'.join(wrap_lines(b64encode(enveloped_data.dump()), 64))

    # Create the resulting message
    result_msg = MIMEText(encoded_content)
    overrides = (
        ('MIME-Version', '1.0'),
        ('Content-Type', 'application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m'),
        ('Content-Transfer-Encoding', 'base64'),
        ('Content-Disposition', 'attachment; filename=smime.p7m')
    )

    for name, value in list(msg.items()):
        if name in [x for x, _ in  overrides]:
            continue
        result_msg.add_header(name, value)

    for name, value in overrides:
        if name in result_msg:
            del result_msg[name]
        result_msg[name] = value

    # return the same type as was passed in
    if passed_as_str:
        return result_msg.as_string()
    else:
        return result_msg
开发者ID:balena,项目名称:python-smime,代码行数:73,代码来源:encrypt.py


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