I made a email sender a few months ago and now I have another project and I wanted to re-test this and for some reason it cannot find the JPG image which is basically in the same directory as the python file..
#Email Module Imports
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
#Imports Time Modules
import time
#Imports Numeric Module Functions
import random
def EmailSender():
#Email Variables
email_user = 'email' # Sender Email (hidden for reason)
email_password = 'password' # Sender Password (hidden for reason)
email_send = 'emailsend' # Receiver Email (hidden for reason)
PORT_EMAIL = 'smtp.gmail.com'
PORT = 587 # Email Port
subject = 'email test'
emailtest = "Test"
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = emailtest
msg.attach(MIMEText(body, 'plain'))
filename = 'download.jpg'
Email_attachment = open(filename, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((Email_attachment).read())
encoders.encode_base64(part)
# adds email header with attachment
part.add_header('Content-Disposition', "attachment; filename= " filename)
msg.attach(part) # attaches email
text = msg.as_string()
srv = smtplib.SMTP(PORT_EMAIL, PORT)
srv.starttls() # runs the email SMTP
srv.login(email_user, email_password)
srv.quit() # stops
EmailSender()
CodePudding user response:
Relative paths (folders) in respect to project has changed. To be fool-proof, change path to jpg with absolute path derived from where the EmailSend.py is located
import os
currentDir= os.path.abspath(os.path.dirname(__file__)) # gets the current pytho file, SendEmail.py and returns absolute path (parent directory)
filepath=os.path.join(currentDir,"download.jpg")
CodePudding user response:
As a follow-up to @jozefow's answer,
import pathlib
cwd = pathlib.Path.cwd()
filepath = cwd / "download.jpeg"
The difference between their answer and mine is that mine does not assume that the current working directory is the same as the file directory. Assumptions either way can be problematic.
The other key difference is mine is nominally more modern python.