Hi all,
I have this function that helps send emails with attachments:
def send_email(…):
…
msg = EmailMessage(
subject, body, send_from,
recipients_list, cc=cc, bcc=bcc,
headers={'Reply-To': reply_to})
msg.attach_alternative(html_body, "text/html")
for f in files:
try:
email_fn, path = f
except (ValueError, TypeError):
path = f
_, email_fn = os.path.split(path)
with open(path, 'rb') as f:
contents = f.read()
msg.attach(email_fn, contents)
msg.send()
In the case where path points to a file with a text mimetype (e.g., 'text/csv'), this fails with this error:
AttributeError: 'bytes' object has no attribute 'encode'
Here's an excerpt from django.core.mail.message. The error occurs on the line 4.
basetype, subtype = mimetype.split('/', 1)
if basetype == 'text':
encoding = self.encoding or settings.DEFAULT_CHARSET
attachment = SafeMIMEText(content, subtype, encoding)
elif basetype == 'message' and subtype == 'rfc822':
# Bug #18967: per RFC2046 s5.2.1, message/rfc822 attachments
# must not be base64 encoded.
if isinstance(content, EmailMessage):
# convert content into an email.Message first
content = content.message()
elif not isinstance(content, Message):
# For compatibility with existing code, parse the message
# into an email.Message object if it is not one already.
content = message_from_string(content)
attachment = SafeMIMEMessage(content, subtype)
else:
# Encode non-text attachments with base64.
attachment = MIMEBase(basetype, subtype)
attachment.set_payload(content)
Encoders.encode_base64(attachment)
return attachment
My question is, why not use base64 encoding if the attachment content is specified as bytes?