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


Python EmailMessage.add_attachment方法代碼示例

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


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

示例1: add_attachment

# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_attachment [as 別名]
    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,代碼行數:27,代碼來源:api.py

示例2: main

# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_attachment [as 別名]
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,代碼行數:60,代碼來源:email-dir.py

示例3: create_mail

# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_attachment [as 別名]
def create_mail(sender, recipient, subject, body, attachments, gpgme_ctx):
    """Create an email either as single or multi-part with attachments.
    """
    msg = EmailMessage(policy=mailgen_policy)
    msg.set_content(body)
    attachment_parent = msg
    if gpgme_ctx is not None:
        msg.make_mixed()
        attachment_parent = next(msg.iter_parts())

    if attachments:
        for args, kw in attachments:
            attachment_parent.add_attachment(*args, **kw)

    if gpgme_ctx is not None:
        signed_bytes = attachment_parent.as_bytes()
        hash_algo, signature = detached_signature(gpgme_ctx, signed_bytes)

        msg.add_attachment(signature, "application", "pgp-signature",
                           cte="8bit")
        # the signature part should now be the last of two parts in the
        # message, the first one being the signed part.
        signature_part = list(msg.iter_parts())[1]
        if "Content-Disposition" in signature_part:
            del signature_part["Content-Disposition"]

        msg.replace_header("Content-Type", "multipart/signed")

        micalg = hash_algorithms.get(hash_algo)
        if micalg is None:
            raise RuntimeError("Unexpected hash algorithm %r from gpgme"
                               % (signature[0].hash_algo,))

        msg.set_param("protocol", "application/pgp-signature")
        msg.set_param("micalg", micalg)

    msg.add_header("From", sender)
    msg.add_header("To", recipient)
    msg.add_header("Subject", subject)
    msg.add_header("Date", formatdate(timeval=None, localtime=True))

    # take the domain part of sender as the domain part of the message
    # ID. We assume that sender has the form [email protected], so we can
    # just the part of sender after the '@'.
    sender_domain = sender.partition("@")[-1]
    if not sender_domain:
        raise RuntimeError("Could not extract the domain from the sender (%r)"
                           " for the Message-ID" % (sender,))
    msg.add_header("Message-Id", make_msgid(domain=sender_domain))

    return msg
開發者ID:Intevation,項目名稱:intelmq-mailgen,代碼行數:53,代碼來源:mail.py

示例4: sendemail

# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_attachment [as 別名]
    def sendemail(self, sender, receiver, subject, body, attachment_name, attachment, maintype='application', subtype='pdf'):
        import smtplib
        from email.message import EmailMessage

        # encodedcontent = base64.b64encode(attachment)  # base64
        #
        #
        # marker = "TRACERDSF123MARKER"
        #
        # # Define the main headers.
        # part1 = "From: <%s>\r\nTo: <%s>\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=%s\r\n--%s\r\n" % (sender, receiver, subject, marker, marker)
        #
        # # Define the message action
        # part2 = "Content-Type: text/plain\r\nContent-Transfer-Encoding:8bit\r\n\r\n%s\r\n--%s\r\n" % (body,marker)
        #
        # # Define the attachment section
        # part3 = "Content-Type: multipart/mixed; name=\"%s\"\r\nContent-Transfer-Encoding:base64\r\nContent-Disposition: attachment; filename=%s\r\n\r\n%s\r\n--%s--\r\n" %(attachment_name, attachment_name, encodedcontent, marker)
        # message = part1 + part2 + part3
        #
        # smtpObj = smtplib.SMTP('localhost')
        # smtpObj.sendmail(sender, receiver, message)
        msg = EmailMessage()
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = receiver

        if body:
            msg.set_content(body)

        # self.info("size{}".format(len(attachment)))
        # print("attachment lenth={}".format(len(attachment)))
        msg.add_attachment(attachment, maintype=maintype, subtype=subtype, filename=attachment_name)

        # Send the email via our own SMTP server.
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)

        self.info("Mailed subject '{}' to {}".format(subject, receiver))
開發者ID:psy0rz,項目名稱:KMUR2,代碼行數:40,代碼來源:Invoices.py

示例5: EmailMessage

# 需要導入模塊: from email.message import EmailMessage [as 別名]
# 或者: from email.message.EmailMessage import add_attachment [as 別名]
# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)
開發者ID:1st1,項目名稱:cpython,代碼行數:31,代碼來源:email-mime.py


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