简体   繁体   中英

unable to send mail in python

I am trying to send a bunch of photos to my email address using the email module. But when I run my program nothing is happening. I am not able to figure out what's wrong in my program. How can I solve this problem?

Python code:

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

fromadd = 'fromadd@gmail.com'
toadd = 'toadd@gmail.com'

def send():
    msg = MIMEMultipart()

    msg['From'] = fromadd
    msg['To'] = toadd
    msg['Subject'] = 'Photos'

    text = MIMEText('Pics')
    msg.attach(text)

    screenshot_data = open(files, 'rb').read()
    webcam_data = open(files, 'rb').read()

    send_image = MIMEImage(screenshot_data, name=os.path.basename(files))
    send_images = MIMEImage(webcam_data, name=os.path.basename(files))

    msg.attach(send_image)
    msg.attach(send_images)

    sessions = smtplib.SMTP('smtp.gmail.com', '587')
    sessions.ehlo()
    sessions.starttls()
    sessions.ehlo()
    sessions.login(fromadd, 'Password')
    sessions.sendmail(fromadd, toadd, msg.as_string())
    sessions.quit()


def main():

    global files

    for files in os.listdir(r'C:\NONE'):

        if os.path.isfile(files) and files.endswith(".jpg"):
            send()
            print('File Sent: ' + files) 
            os.remove(files)

    else:
        pass

 if __name__ == '__main__':
     main()

os.listdir() returns just the file names, not the full paths. So unless you run this program in c:\\NONE or just happen to have a file with the same name in your current working directory, os.path.isfile(files) will return False , and so send() will never be called.

Even though it's not specific to Python - so many of the concrete tips in it do not apply - you might want to give Eric Lippert's How To Debug Small Programs a read. Also remember Brian Kernighan's advice:

The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.

-- "Unix for Beginners" (1979)

The immediate fix is to os.path.join() the directory name back in front; but you also really need to get rid of the global variable.

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

fromadd = 'fromadd@gmail.com'
toadd = 'toadd@gmail.com'

def send(pathname, froma, toa):
    msg = MIMEMultipart()

    msg['From'] = froma
    msg['To'] = toa
    msg['Subject'] = 'Photos'

    text = MIMEText('Pics')
    msg.attach(text)

    # Should really close() when done!
    screenshot_data = open(pathname, 'rb').read()
    webcam_data = open(pathname, 'rb').read()

    screenshot_image = MIMEImage(screenshot_data, name=os.path.basename(pathname))
    webcam_image = MIMEImage(webcam_data, name=os.path.basename(pathname))

    msg.attach(screenshot_image)
    msg.attach(webcam_image)

    session = smtplib.SMTP('smtp.gmail.com', '587')
    session.ehlo()
    session.starttls()
    session.ehlo()
    session.login(froma, 'Password')
    session.sendmail(froma, toa, msg.as_string())
    session.quit()

def main():
    for basename in os.listdir(r'C:\NONE'):
        filename = os.path.join([r'C:\NONE', basename])
        # switch order of conditions for minor efficiency hack
        if filename.endswith(".jpg") and os.path.isfile(filename):
            send(filename, fromadd, toadd)
            print('File Sent: ' + filename) 
            os.remove(filename)
        # empty else not required

 if __name__ == '__main__':
     main()

Notice also how I renamed several of the variables to avoid plurals on singular instances and hopefully better connect related variables by using a common prefix.

It's still not clear why you send two copies of each image, or why you create a text part when you don't have anything useful to put in it. You might also want to avoid the legacy sendmail method in accordance with the recommendation in its documentation. And why do you create a separate message for each photo? Attaching all the photos to a single email message will surely be more practical (unless the pics are absolutely huge and the message becomes too big for your mail server; but surely then email is the wrong tool for this anyway).

More fundamentally, you should not be writing new code in Python 2 in 2018; and incidentally, some of this would be somewhat more straightforward with the overhauled email library in 3.6+ (though it's still low-level and quirky).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM