Python Forum
How to release control of file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to release control of file
#1
I'm able to send an email with the script below just fine, but when it's grabbing the attachment it's doesn't close the connection to the file. Can somebody point out where or how to release/close the connection?

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
import os.path
import pathlib
import time


def send_voicemail(path):
    email = '[email protected]'
    password = 'somepassword'
    send_to_email = '[email protected]'
    subject = 'New Voice Mail: ' + str("created: %s" % time.ctime(os.path.getctime(path)))
    message = 'Your new message is attached.'
    file_location = path
    
    msg = MIMEMultipart()
    msg['From'] = email
    msg['To'] = send_to_email
    msg['Subject'] = subject
    msg.attach (MIMEText(message, 'plain'))
    

    filename = os.path.basename(file_location)
    attachment = open(file_location, "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    msg.attach(part)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(email,password)
    text = msg.as_string()
    server.sendmail(email,send_to_email, text)
    server.quit()
    server.close() #not sure what this does.
#Cant do anything with the file even after the connection to the server is closed.
Reply
#2
You should just be able to replace
    attachment = open(file_location, "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
with
    part = MIMEBase('application', 'octet-stream')
    with open(file_location, "rb") as attachment:
        part.set_payload(attachment.read())
You could also explicit call attachment.close() after you read from the file, but context managers (the with-block here) are usually preferred.
Reply
#3
HaZaaa!
Thank you. That did it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to get mouse coordinates on click and release OhNoSegFaultAgain 1 2,988 May-17-2019, 06:56 PM
Last Post: buran
  Python 3.4: the only release to create .EXE standalone without .dll samsonite 7 5,792 Feb-28-2019, 09:20 AM
Last Post: samsonite
  Release kbhit Epilepsy 2 4,301 May-26-2018, 10:47 AM
Last Post: snippsat
  How to release Memory of GPU! majinbuu 1 2,605 May-11-2018, 05:06 AM
Last Post: j.crater
  3.6.2 is latest stable release right? And "path length" Fran_3 3 3,317 Aug-01-2017, 02:04 PM
Last Post: Fran_3
  How to I make my program release memory? Plecto 11 10,680 Dec-18-2016, 10:03 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020