santos_the1st
santos_the1st

Reputation: 3

Email sending without attachment - Python 3.8

  1. I want to send a .txt file attached to the mail in Python. Currently the mail is received but without any attachment.
  2. Code bellow
  3. I've sent emails in PHP but Python is completely new to me
  4. The code doesn't return any errors, it simply doesn't send the attachment with the email
   with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
       server = smtplib.SMTP('smtp.gmail.com', 587) 
       smtp.ehlo()
       smtp.starttls()
       smtp.ehlo()
       msg = MIMEMultipart()

       smtp.login(EMAIL_ADRESS, EMAIL_PASSWORD)
       subject = 'Log Register'

       
       filename = 'logs-to-h4wtsh0wt.txt'
       attachment = open(filename, 'rb')
       part = MIMEBase('application', 'octet-stream')
       part.set_payload(attachment.read())
       encoders.encode_base64(part)
       part.add_header('Content-Disposition', "attachment; filename= "+filename)
       msg.attach(part)
       msg = f'Subject: {subject}\n\n{Body}'
       smtp.sendmail(EMAIL_ADRESS,EMAIL_ADRESS, msg)

Upvotes: 0

Views: 1248

Answers (1)

karopolopoulos
karopolopoulos

Reputation: 76

snakecharmerb is right. You are indeed overriding the message object and therefore losing everything you add before that point.

You can instead set the subject like this:

msg['Subject'] = "Subject of the Mail"

# string to store the body of the mail 
body = "Body_of_the_mail"
  
# attach the body with the msg instance 
msg.attach(MIMEText(body, 'plain')) 

Because you are attaching a file you will also need to convert the multipart message into a string before sending:

text = msg.as_string()

smtp.sendmail(fromaddr, toaddr, text) 

When you created msg with MIMEMultipart() it generated the message object structure for you as per RFC2822 which also gives you FROM, TO, etc.

The msg object also has a bunch of functions you can run outlined in its docs

Upvotes: 2

Related Questions