Search code examples
pythonemail-attachmentsmimemimemultipart

What is causing my 'test.txt' file being sent from Python to my gmail account to come across as "Untitled" when I receive it in my email inbox?


I am sending a file called test.txt as an attachment below through the python program. It successfully sends but when I receive it in my Gmail inbox the attached file says Untitled instead of text.txt. I have my email block of code below and it looks correct. Any suggestions?

# Setup the email
mail_content = '''Hello,
The attached document contains the results of the file scan.
Please contact the IT Help Desk if you have any questions.
Thank You!!!
'''
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'A test mail sent by Python. It has an attachment.'
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'david.txt'
# attach_file_name = file_name
attach_file = open(attach_file_name, 'rb')  # Open the file as binary mode

# Setup the Payload
payload = MIMEBase('application', 'octate-stream')
payload.set_payload(attach_file.read())
encoders.encode_base64(payload)  # encode the attachment
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)

# Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587)  # use gmail with port
session.starttls()  # enable security
session.login(sender_address, sender_pass)  # login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()

Screen capture of the email I received:
Received email


Solution

  • Because spelling matters. It's not "octate-stream", it's "octet-stream", and it's not "Content-Decomposition", it's "Content-Disposition".