Home > other >  smtplib email file attachment is being defaulted to 'noname'
smtplib email file attachment is being defaulted to 'noname'

Time:01-13

I am trying to automate some email sending with python and the smtplib library. Currently, it sends the email fine and attaches the file, but the file does not keep the name that I set.

  #The body and the attachments for the mail
  message.attach(MIMEText(mail_content, 'plain'))
  attach_file_name = 'temp.txt'
  attach_file = open(attach_file_name, 'rb') # Open the file as binary mode
  payload = MIMEBase('application', 'octate-stream')
  payload.set_payload((attach_file).read())
  encoders.encode_base64(payload) #encode the attachment
  #add payload header with filename
  payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
  message.attach(payload)

  #Create SMTP session for sending the mail
  session = smtplib.SMTP('-----', 587) #custom domain
  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()
  print('Mail Sent')

The above code should set the attachment file name to "temp.txt" I believe, but it defaults to "noname" in the inbox that it is sent to.

CodePudding user response:

I found a solution using MIMEApplication - it correctly names the attachment.

attach_file_name = 'Test.pdf'
attach_file=MIMEApplication(open(attach_file_name,"rb").read())
attach_file.add_header('Content-Disposition', 'attachment', filename=attach_file_name)
message.attach(attach_file)
  • Related