當前位置: 首頁>>代碼示例>>Python>>正文


Python message.EmailMessage類代碼示例

本文整理匯總了Python中email.message.EmailMessage的典型用法代碼示例。如果您正苦於以下問題:Python EmailMessage類的具體用法?Python EmailMessage怎麽用?Python EmailMessage使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了EmailMessage類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: add_attachment

    def add_attachment(cls, msg: EmailMessage, content: bytes, filename: str,
                       mimetype: str = None):
        """
        Add binary data as an attachment to an :class:`~email.message.EmailMessage`.

        The default value for the ``mimetype`` argument is guessed from the file name.
        If guessing fails, ``application/octet-stream`` is used.

        :param msg: the message
        :param content: the contents of the attachment
        :param filename: the displayed file name in the message
        :param mimetype: the MIME type indicating the type of the file

        """
        assert check_argument_types()
        if not mimetype:
            mimetype, _encoding = guess_type(filename, False)
            if not mimetype:
                mimetype = 'application/octet-stream'

        maintype, subtype = mimetype.split('/', 1)
        if not maintype or not subtype:
            raise ValueError('mimetype must be a string in the "maintype/subtype" format')

        msg.add_attachment(content, maintype=maintype, subtype=subtype, filename=filename)
開發者ID:asphalt-framework,項目名稱:asphalt-mailer,代碼行數:25,代碼來源:api.py

示例2: do_genmime

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,代碼行數:25,代碼來源:render.py

示例3: send_email

    def send_email(self, recipient_email, subject, body):
        """Sends an email to a defined address. """
        
        # prepare message
        msg = EmailMessage()
        msg['Subject'] = subject
        msg['From'] = Address(self.sender_email) #self.sender_name, addr_spec=
        msg['To'] = Address(self.sender_name, recipient_email)

        msg.set_content(body)

        '''
        message = MIMEText(body)
        message["Subject"] = subject 
        message["From"] = self.mail
        message["To"] = recipient_email
        msg = message.as_string()
        '''
        
        server = smtplib.SMTP(self.server)
        
        if self.use_tls: # deliberately starts tls if using TLS
            server.ehlo()
            server.starttls()
            server.ehlo()
            
        server.login(self.login, self.password) 
        server.send_message(msg)
        server.quit()
        return
開發者ID:lenarother,項目名稱:pyhome,代碼行數:30,代碼來源:send_email.py

示例4: make_message_object

def make_message_object(origin, destination, subject, content):
    m = EmailMessage()
    m.set_content(content)
    m['Subject'] = subject
    m['From'] = origin
    m['To'] = destination
    return m
開發者ID:PhilippeCarphin,項目名稱:tests,代碼行數:7,代碼來源:test_email.py

示例5: MHTML

class MHTML(object):
    def __init__(self):
        self._msg = EmailMessage()
        self._msg['MIME-Version'] = '1.0'
        self._msg.add_header('Content-Type', 'multipart/related', type='text/html')

    def add(self, location: str, content_type: str, payload: str, encoding: str = 'quoted-printable') -> None:
        resource = EmailMessage()
        if content_type == 'text/html':
            resource.add_header('Content-Type', 'text/html', charset='utf-8')
        else:
            resource['Content-Type'] = content_type
        if encoding == 'quoted-printable':
            resource['Content-Transfer-Encoding'] = encoding
            resource.set_payload(quopri.encodestring(payload.encode()))
        elif encoding == 'base64':
            resource['Content-Transfer-Encoding'] = encoding
            resource.set_payload(base64.b64encode(payload))
        elif encoding == 'base64-encoded':  # Already base64 encoded
            resource['Content-Transfer-Encoding'] = 'base64'
            resource.set_payload(payload)
        else:
            raise ValueError('invalid encoding')
        resource['Content-Location'] = location
        self._msg.attach(resource)

    def __str__(self) -> str:
        return str(self._msg)

    def __bytes__(self) -> bytes:
        return bytes(self._msg)
開發者ID:bosondata,項目名稱:prerender,代碼行數:31,代碼來源:mhtml.py

示例6: flush

    def flush(self):
        self.acquire()
        try:
            if len(self.buffer) > 0:
                import smtplib
                from email.message import EmailMessage
                import email.utils

                port = self.mailport
                if not port:
                    port = smtplib.SMTP_PORT
                smtp = smtplib.SMTP(
                    self.mailhost, port, timeout=self.smtp_timeout)
                msg = EmailMessage()
                msg['From'] = self.fromaddr
                msg['To'] = ','.join(self.toaddrs)
                msg['Subject'] = self.getSubject(self.buffer)
                msg['Date'] = email.utils.localtime()
                msg.set_content('\n'.join(self.format(r) for r in self.buffer))
                if self.username:
                    if self.secure is not None:
                        smtp.ehlo()
                        smtp.starttls(*self.secure)
                        smtp.ehlo()
                    smtp.login(self.username, self.password)
                smtp.send_message(msg)
                smtp.quit()
                self.buffer = []
        except Exception:
            self.handleError(self.buffer[-1])
        finally:
            self.release()
開發者ID:dougalsutherland,項目名稱:PreviouslyTV-helper,代碼行數:32,代碼來源:deploy_base.py

示例7: _send

    def _send(self, msg_content):
        # reference
        # - https://docs.python.org/3/library/email-examples.html
        send_msg = EmailMessage()
        send_msg['From'] = self.email_from

        # multiple mail_to
        #  ex) [email protected],[email protected]
        send_msg['To'] = self.email_to

        if len(self.email_cc) > 0:
            send_msg['CC'] = self.email_cc

        send_msg['Subject'] = self.subject
        send_msg.set_content(msg_content)

        s = smtplib.SMTP(self.smtp_server, self.smtp_port)

        # Hostname to send for this command defaults
        #  to the fully qualified domain name of the local host.
        s.ehlo()

        # Puts connection to SMTP server in TLS mode
        s.starttls()
        s.ehlo()

        s.login(self.smtp_account, self.smtp_password)
        s.set_debuglevel(1)

        s.send_message(send_msg)
        s.quit()
開發者ID:morenice,項目名稱:excellent,代碼行數:31,代碼來源:email_sender.py

示例8: sendEmail

def sendEmail(args, returnCode):
    """
    Try to send an email to the user. Errors must be non-fatal.
    """
    try:
        import smtplib
        from email.message import EmailMessage
        msg = EmailMessage()
        msg['Subject'] = "Snakepipes completed"
        msg['From'] = args.emailSender
        msg['To'] = args.emailAddress
        if returnCode == 0:
            msg.set_content("The pipeline finished successfully\n")
        else:
            msg.set_content("The pipeline failed with exit code {}\n".format(returnCode))

        if args.onlySSL:
            s = smtplib.SMTP_SSL(args.smtpServer, port=args.smtpPort)
        else:
            s = smtplib.SMTP(args.smtpServer, port=args.smtpPort)
        if args.smtpUsername:
            s.login(args.smtpUsername, args.smtpPassword)
        s.send_message(msg)
        s.quit()
    except:
        sys.stderr.write("An error occured while sending the email.\n")
        pass
開發者ID:kilpert,項目名稱:snakemake_workflows,代碼行數:27,代碼來源:common_functions.py

示例9: flush

 def flush(self):
      # Add extra newline to info() messages for separation in logfile
      if not self.buffer:
           _logger.info("No warnings, no email to send\n")
           return
      _logger.info(f"Sending logging email with {len(self.buffer)} records\n")
      txt = ''.join(self.format(record)+'\n' for record in self.buffer)
      msg = EmailMessage()
      msg['Subject'] = "mfaliquot: {}.py has something to say".format(self.scriptname)
      msg['To'] = ', '.join(self.to_addrs)
      msg['From'] = self.from_addr
      msg.set_content("Something went wrong (?) while {}.py was running:\n\n".format(self.scriptname)+txt)
      try:
           s = SMTP()
           s.connect(self.host, self.port)
           s.starttls()
           if self.username and self.password:
                s.login(self.username, self.password)
           s.send_message(msg)
           s.quit()
      except SMTPException as e:
           _logger.exception("Logging email failed to send:", exc_info=e, extra=self._special_kwarg)
      except OSError as e:
           _logger.exception("Some sort of smtp problem:", exc_info=e, extra=self._special_kwarg)
      except BaseException as e:
           _logger.exception("Unknown error while attempting to email:", exc_info=e, extra=self._special_kwarg)
      else:
           self.buffer.clear()
開發者ID:dubslow,項目名稱:MersenneForumAliquot,代碼行數:28,代碼來源:__init__.py

示例10: test_send_message_uses_smtputf8_if_addrs_non_ascii

    def test_send_message_uses_smtputf8_if_addrs_non_ascii(self):
        msg = EmailMessage()
        msg['From'] = "Páolo <fő[email protected]>"
        msg['To'] = 'Dinsdale'
        msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
        # XXX I don't know why I need two \n's here, but this is an existing
        # bug (if it is one) and not a problem with the new functionality.
        msg.set_content("oh là là, know what I mean, know what I mean?\n\n")
        # XXX smtpd converts received /r/n to /n, so we can't easily test that
        # we are successfully sending /r/n :(.
        expected = textwrap.dedent("""\
            From: Páolo <fő[email protected]>
            To: Dinsdale
            Subject: Nudge nudge, wink, wink \u1F609
            Content-Type: text/plain; charset="utf-8"
            Content-Transfer-Encoding: 8bit
            MIME-Version: 1.0

            oh là là, know what I mean, know what I mean?
            """)
        smtp = smtplib.SMTP(
            HOST, self.port, local_hostname='localhost', timeout=3)
        self.addCleanup(smtp.close)
        self.assertEqual(smtp.send_message(msg), {})
        self.assertEqual(self.serv.last_mailfrom, 'fő[email protected]')
        self.assertEqual(self.serv.last_rcpttos, ['Dinsdale'])
        self.assertEqual(self.serv.last_message.decode(), expected)
        self.assertIn('BODY=8BITMIME', self.serv.last_mail_options)
        self.assertIn('SMTPUTF8', self.serv.last_mail_options)
        self.assertEqual(self.serv.last_rcpt_options, [])
開發者ID:CCNITSilchar,項目名稱:cpython,代碼行數:30,代碼來源:test_smtplib.py

示例11: create_msg

def create_msg(recv: str, subject: str, body: str, sender: str=SENDER_EMAIL) -> EmailMessage:
    msg = EmailMessage()
    msg['To'] = recv
    msg['From'] = sender
    msg['Subject'] = subject
    msg.set_content(body)

    return msg
開發者ID:thismachinechills,項目名稱:cheapbook,代碼行數:8,代碼來源:send.py

示例12: sample_message

def sample_message():
    msg = EmailMessage()
    msg['From'] = '[email protected]'
    msg['To'] = 'Test Recipient <[email protected]>, [email protected]'
    msg['Cc'] = 'Test CC <[email protected]>, [email protected]'
    msg['Bcc'] = 'Test BCC <[email protected]>, [email protected]'
    msg.set_content('Test content')
    return msg
開發者ID:asphalt-framework,項目名稱:asphalt-mailer,代碼行數:8,代碼來源:conftest.py

示例13: main

def main():
    parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_argument('-d', '--directory',
                        help="""Mail the contents of the specified directory,
                        otherwise use the current directory.  Only the regular
                        files in the directory are sent, and we don't recurse to
                        subdirectories.""")
    parser.add_argument('-o', '--output',
                        metavar='FILE',
                        help="""Print the composed message to FILE instead of
                        sending the message to the SMTP server.""")
    parser.add_argument('-s', '--sender', required=True,
                        help='The value of the From: header (required)')
    parser.add_argument('-r', '--recipient', required=True,
                        action='append', metavar='RECIPIENT',
                        default=[], dest='recipients',
                        help='A To: header value (at least one required)')
    args = parser.parse_args()
    directory = args.directory
    if not directory:
        directory = '.'
    # Create the message
    msg = EmailMessage()
    msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
    msg['To'] = ', '.join(args.recipients)
    msg['From'] = args.sender
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # 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)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    if args.output:
        with open(args.output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)
開發者ID:1st1,項目名稱:cpython,代碼行數:58,代碼來源:email-dir.py

示例14: send_email

def send_email(email, subject, message):
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = '[email protected]'
    msg['To'] = email
    msg.set_content(message)

    with smtplib.SMTP('localhost') as s:
        s.send_message(msg)
開發者ID:Braedon,項目名稱:up,代碼行數:9,代碼來源:up.py

示例15: combine

def combine(body, attachments):
    message = EmailMessage()
    message.add_related(body, subtype='html')
    for attachment in attachments:
        cid = attachment['cid']
        buffer = attachment['buffer']
        img = MIMEImage(buffer.read(), _subtype='png')
        img.add_header('Content-ID', cid)
        message.attach(img)
    return message
開發者ID:zalando-stups,項目名稱:costreport,代碼行數:10,代碼來源:costreport.py


注:本文中的email.message.EmailMessage類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。