Oct-03-2018, 05:18 PM
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.
