I am trying to implement a mailer in python, which will run as a lambda function, but all my files that are getting delivered in the mail are corrupt and are not opening, except for txt files.
mail = MIMEMultipart()
# mail = EmailMessage()
mail['To'] = data['to']
mail['From'] = sender
mail['Subject'] = populate_data_to_string(data['subject_data'], subject)
body = MIMEText(populate_data_to_string(data['data'], template), 'html')
mail.attach(body)
mail = load_attachments(mail, files)
mail = {'raw': base64.urlsafe_b64encode(mail.as_bytes()).decode()}
I am loading attachments as follows, Mind that file here is a FieldStorage
object
def load_attachments(mail, files):
for file in files: # file is a FieldStorage
content_type, encoding = mimetypes.guess_type(file.filename)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text':
attachment = MIMEText('r', _subtype=sub_type)
elif main_type == 'image':
attachment = MIMEImage('r', _subtype=sub_type)
elif main_type == 'audio':
attachment = MIMEAudio('r', _subtype=sub_type)
else:
attachment = MIMEBase(main_type, sub_type)
attachment.set_payload(file.value)
filename = file.filename
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
mail.attach(attachment)
return mail
This mail is being sent using Gmail APIs