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


Python EmailMessage.add_alternative方法代码示例

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


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

示例1: do_genmime

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
def do_genmime(args):
    """Execute the ``genmime`` subcommand. Unlike ``genhtml``, this command
    inlines images (which ``genhtml`` can't do becaus ``cid`` embedding is not,
    AFAIK, usable outside of email clients, but ``genhtml`` is most useful for
    previewing emails in browsers!)."""
    # Set up the email
    md_source = args.source.read()
    mail = EmailMessage()
    mail["From"] = Address(args.sender_name, args.sender_email)
    issue_no, _, _ = load_issue(md_source)
    mail["Subject"] = "Frontiers Fortnightly #{}".format(issue_no)

    # First, produce the text part
    text_content = render_mail_template(md_source, TEXT_TEMPLATE_NAME, args.sender_name, args.sender_email)
    mail.set_content(text_content)

    # Next, produce the HTML part
    minified_html = generate_html(md_source, HTML_TEMPLATE_NAME, args.sender_name, args.sender_email)
    inlined_html = inline_images(minified_html)
    mail.add_alternative(inlined_html, subtype="html")

    if "b" in args.dest.mode:
        args.dest.write(bytes(mail))
    else:
        args.dest.write(str(mail))
开发者ID:anu-maker-club,项目名称:newsletter,代码行数:27,代码来源:render.py

示例2: _prepare_message

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
	def _prepare_message(self):
		msgs = []
		for rec_group in self.recipients:
			msg = EmailMessage()
			msg['From'] = self.frm
			msg['To'] = rec_group
			content = self.content
			msg['Subject'] = content['meta']['subject'][0]
			msg.set_content(content['raw'])
			msg.add_alternative(content['html'], subtype='html')
			msgs.append(msg)
		return msgs
开发者ID:pirati-cz,项目名称:byro,代码行数:14,代码来源:mail.py

示例3: send_email

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
def send_email(
    email_from: str,
    email_to: str,
    location: Location,
    screenshot: MapScreenshot,
    template: str = None,
) -> None:
    """
    Send the traffic info email.

    Args:
        email_from: Email sender's address.
        email_to: Email recipient's address.
        location: The map's location.
        screenshot: The map's screenshot.
        template: The path to the email's Jinja2 template,
        templates/email.j2 if not specified.

    """
    if template is None:
        template = os.path.join(DIR, "templates", "email.j2")
    logger = logging.getLogger(__name__)
    map_cid = make_msgid()
    context: Context = {
        "url": f"https://www.google.fr/maps/@{location.latitude},"
        f"{location.longitude},{location.zoom}z/data=!5m1!1e1",
        "width": screenshot.width,
        "height": screenshot.height,
        "map_cid": map_cid[1:-1],
    }
    content = f"""
    Today's traffic conditions.
    {context["url"]}
    Have a safe trip back home!
    """
    html = render_template(template, context)
    email = EmailMessage()
    email["Subject"] = "Traffic info"
    email["From"] = Address("Traffic info", addr_spec=email_from)
    email["To"] = email_to
    email.set_content(content)
    email.add_alternative(html, subtype="html")
    with open(screenshot.path, "rb") as img:
        email.get_payload()[1].add_related(img.read(), "image", "png", cid=map_cid)

    try:
        with smtplib.SMTP("localhost") as smtp:
            smtp.send_message(email)
    except ConnectionRefusedError as exception:
        logger.error("Unable to send email(%s)", exception)
开发者ID:Da-Juan,项目名称:traffic_info,代码行数:52,代码来源:core.py

示例4: create_message

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
    def create_message(self, *, subject: str = None, sender: Union[str, Address] = None,
                       to: AddressListType = None, cc: AddressListType = None,
                       bcc: AddressListType = None, charset: str = None, plain_body: str = None,
                       html_body: str = None) -> EmailMessage:
        """
        Create an :class:`~email.message.EmailMessage` using to be sent later using
        :meth:`deliver`.

        :param subject: subject line for the message
        :param sender: sender address displayed in the message (the From: header)
        :param to: primary recipient(s) (displayed in the message)
        :param cc: secondary recipient(s) (displayed in the message)
        :param bcc: secondary recipient(s) (**not** displayed in the message)
        :param charset: character encoding of the message
        :param plain_body: plaintext body
        :param html_body: HTML body

        """
        assert check_argument_types()
        msg = EmailMessage()
        msg['Subject'] = subject or self.message_defaults.get('subject')

        sender = sender or self.message_defaults.get('sender')
        if sender:
            msg['From'] = sender

        to = to or self.message_defaults.get('to')
        if to:
            msg['To'] = to

        cc = cc or self.message_defaults.get('cc')
        if cc:
            msg['Cc'] = cc

        bcc = bcc or self.message_defaults.get('bcc')
        if bcc:
            msg['Bcc'] = bcc

        charset = charset or self.message_defaults.get('charset')
        if plain_body is not None and html_body is not None:
            msg.set_content(plain_body, charset=charset)
            msg.add_alternative(html_body, charset=charset, subtype='html')
        elif plain_body is not None:
            msg.set_content(plain_body, charset=charset)
        elif html_body is not None:
            msg.set_content(html_body, charset=charset, subtype='html')

        return msg
开发者ID:asphalt-framework,项目名称:asphalt-mailer,代码行数:50,代码来源:api.py

示例5: contact

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
def contact():
    def error(message):
        response = jsonify(message=message)
        response.status_code = 400
        return response

    name = request.form.get('name', None)
    email_addr = request.form.get('email', None)
    phone = request.form.get('phone', '없음')
    message = request.form.get('message', None)

    if name is None:
        return error('이름을 적어주세요')

    if email_addr is None:
        return error('메일주소를 적어주세요')

    if message is None:
        return error('본문을 적어주세요')

    context = render_template(
        'response.html',
        name=name,
        email_addr=email_addr,
        phone=phone,
        message=message
    )

    msg = EmailMessage()
    msg['Subject'] = "고객님의 신규 상담이 접수되었습니다."
    msg['From'] = Address('Snoin', '[email protected]')
    msg['To'] = app.config['MAIL_LISTENERS'] + [Address(name, email_addr)]

    msg.set_content('접수되었습니다.')
    msg.add_alternative(context, subtype='html')

    try:
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s:
            s.ehlo()
            s.login(app.config['SMTP_ID'], app.config['SMTP_PASSWORD'])
            s.send_message(msg)
    except smtplib.SMTPException as e:
        return error(str(e))

    return jsonify(message='접수되었습니다.')
开发者ID:Snoin,项目名称:snoin.com,代码行数:47,代码来源:app.py

示例6: send

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
def send(recipient):
    """
    Send demo credentials to recipient
    """
    # Create the base text message.
    msg = EmailMessage()
    msg['Subject'] = "Connexion démo LabResult "
    msg['From'] = Address("", "[email protected]")
    msg['To'] = (Address("", recipient),)
    msg.set_content(mail_tmplt_txt.content)

    logo_cid = str(uuid.uuid4())
    msg.add_alternative(mail_tmplt_html.content.format(logo_cid=logo_cid),
            'html', 'utf-8')
    # Now add the related image to the html part.
    logo = os.path.join(os.path.dirname(__file__), "data", "logo.png")
    with open(logo, 'rb') as img:
        msg_image = MIMEImage(img.read(), name=os.path.basename(logo),
                _subtype="image/png" )
        msg.attach(msg_image)
        msg_image.add_header('Content-ID', '<{}>'.format(logo_cid))

    msg2 = MIMEText("Envoi des identifians de démo à %s" % recipient)
    msg2['Subject'] = "Connexion démo LabResult "
    msg2['From'] = "[email protected]"
    msg2['To'] = "[email protected]"
    # Send the message via local SMTP server.
    ret = False
    try :
        smtp_server = get_option('smtp_server', 'mail.gandi.net')
        with smtplib.SMTP_SSL(smtp_server) as s:
            USERNAME = get_option('smtp_login', '[email protected]')
            PASSWORD = get_option('smtp_password','pacman9732')
            s.login(USERNAME, PASSWORD)
            s.send_message(msg)
            s.send_message(msg2)
            ret = True
    except Exception :
        labresult.app.logger.error(traceback.format_exc())
    finally:
        return ret
开发者ID:sladinji,项目名称:LabResult,代码行数:43,代码来源:mail.py

示例7: send

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
 def send(self):
     try:
         msg = EmailMessage()
         msg['Date'] = formatdate()
         msg['Subject'] = self.subject
         msg['From'] = Address('Alpha Geeks', *self.sender.split('@'))
         msg['To'] = tuple(
             Address('System Admin', *t.split('@')) for t in self.to
         )
         msg.set_content(self.content)
         if self.html is not None:
             msg.add_alternative("""<html>
             <head><title>{title}</title>
             </head><body><pre>{body}</pre>
             </body></html>
             """.format(
                 title=self.subject,
                 body=self.html
             ), subtype='html')
         with SMTP(self.server) as con:
             con.login(self.user, self.passwd)
             con.send_message(msg)
     except Exception as e:
         sys.exit("mail failed: %s" % str(e))
开发者ID:alphageek-xyz,项目名称:bin,代码行数:26,代码来源:mailer.py

示例8: make_msgid

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Add the html version.  This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
  <head></head>
  <body>
    <p>Salut!<\p>
    <p>Cela ressemble à un excellent
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718>
            recipie
        </a> déjeuner.
    </p>
    <img src="cid:{asparagus_cid}" \>
  </body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
开发者ID:willingc,项目名称:tone-tuner,代码行数:34,代码来源:emailcreator.py

示例9: deliver_email

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
    def deliver_email(self, id, rx, msgbody, status_recorder):
        ''' gateway gives us plenty of info, what we want out of it is:
              date_created, error_code, error_message, sid, status

              we'll parse the error_code and error_message and return them in sendStatus
        '''
        urgheaders = [
           ('Priority','Urgent'),
           ('X-Priority','1 (Highest)'),
           ('Importance','High'),
           ('X-MMS-Priority','Urgent')
        ]

        emailheaders = [
           ('To', 'SMVFD'),
           ('From', 'DispatchBuddy <[email protected]>'),
           ('Subject', 'Fire Dispatch: {address}'.format(address=self.evdict['address'])),
        ]

        send_results = []

        now = datetime.datetime.utcnow()

        msg = EmailMessage()
        for h,v in emailheaders:
            msg[h]=v

        msg.set_content('This is an HTML only email')
        magnify_icon_cid = make_msgid()

        medias = []
        fdict  = {'meta_icons':'', 'magnify_icon_cid':magnify_icon_cid[1:-1]}

        self.logger.debug('ADD MMS urls, search for keys in: {}'.format(self.evdict['nature']))
        for rk in sorted(media_urls):
            if re.search(rk, self.evdict['nature']) or re.search(rk, self.evdict['notes']):
                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')
#.........这里部分代码省略.........
开发者ID:Blue-Labs,项目名称:DispatchBuddy,代码行数:103,代码来源:gateways.py

示例10: send_email_credential

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
def send_email_credential(user):
    """
    Send credentials to user
    :param user: :class:`labresult.model.User`
    """
    if not user.email :
        labresult.app.logger.warning("%s has no email" % user.email)
        return False

    # wait ten minutes between to sending
    for message in [ m for m in user.messages if m.title == "credential" and
            m.channel == "email" ]:
        if (now() - message.date) < timedelta(
                minutes=get_option('crendential_email.tempo', 10,
    gettext("Minutes avant l'envoi d'un deuxieme email"))):
            labresult.app.logger.warning("Credential email already sent to %s" % user.email)
            return True
    # Create the base text message.
    msg = EmailMessage()
    msg['Subject'] = get_option("credential_email.title",
        gettext("Accès à mes résultats"))
    msg['From'] = Address("",
            get_option('crendential_email.from_address',
                "[email protected]",
                gettext("Adresse email de l'envoyeur."),
                )
            )
    msg['To'] = (Address("", user.email),)
    #generate txt from html
    template = get_option("credential_email.html_content",
            credential.html_content,
            gettext("Contenu du mail d'authentification"),
            )
    txt_content = re.sub("<[^>]+>",
            "",
            template.replace("<br>",'\n').format(code=user.credential_code,
                logo_cid=""))

    msg.set_content(txt_content)

    logo_cid = str(uuid.uuid4())
    msg.add_alternative(template.format(logo_cid=logo_cid,
        code = user.credential_code),
            'html', 'utf-8')
    # Now add the related image to the html part.
    default_logo = open(os.path.join(os.path.dirname(__file__), "data",
        "logo.png"), 'rb').read()
    logo = get_option("credential_email.logo", default_logo)
    msg_image = MIMEImage(logo, name='logo.png',
            _subtype="image/png" )
    msg.attach(msg_image)
    msg_image.add_header('Content-ID', '<{}>'.format(logo_cid))
    # Send the message via local SMTP server.
    try :
        with smtplib.SMTP_SSL(get_option("smtp_server")) as s:
            s.login(get_option("smtp_login"), get_option("smtp_password"))
            s.send_message(msg)
            log_message(user, "credential", "email", get_option("smtp_server"),
                    txt_content)
            return True
    except Exception :
        error = traceback.format_exc()
        labresult.app.logger.error(error)
        return False
开发者ID:sladinji,项目名称:LabResult,代码行数:66,代码来源:email.py

示例11:

# 需要导入模块: from email.message import EmailMessage [as 别名]
# 或者: from email.message.EmailMessage import add_alternative [as 别名]
msg.add_alternative("""\
<html>
  <head></head>
  <body>
    <p>Bonjour,</p>

<p>Pour accéder au site de démonstration LabResult, vous pouvez utiliser les identifiants suivant:</p>
<ul>
 <li> patient :
  <ul>
  <li> identifiant  : patient</li>
  <li> mot de passe : password</li>
  </ul>
 </li>
<br>
 <li> médecin :
  <ul>
  <li> identifiant  : docteur</li>
  <li> mot de passe : password</li>
  </ul>
 </li>
<br>
 <li> biologiste :
  <ul>
  <li> identifiant  : biologiste</li>
  <li> mot de passe : password</li>
  </ul>
 </li>
</ul>

LabResult<br>
Tel : 07 82 42 32 12
<br>
    <img src="cid:{logo_cid}" \>
  </body>
</html>
""".format(logo_cid=logo_cid[1:-1]), subtype='html')
开发者ID:sladinji,项目名称:LabResult,代码行数:39,代码来源:testmail.py


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