本文整理汇总了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)
示例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)
示例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
示例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))
示例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)