简体   繁体   中英

Error sending an email through gmail via python

Hello!

I am trying to do a program in Python that would receive an email address and some phrase in command line arguments and the program would send the phrase (with some background information) to the email address provided.

Ths code is the following:

#Mail Module
try:
    import smtplib
    import sys
    from email.mime.text import MIMEText
except ImportError:
    print "Error importing necessary modules into the project, Please contact MagshiProject staff"
else:
    def sendAnEmail():
        try:
            sender      = "magshiproject@gmail.com"
            recipient   = str(sys.argv[1])
            password    = str(sys.argv[2])
            message     = MIMEText("""From: From Magshimim Project <magshiproject@gmail.com>
                            To: To User <'{0}'>
                            Subject: Your password to further use MagshiProject Program

                            Your password is: '{1}'
                            Please copy and paste it from here to the window requesting this password in order to proceed.
                            This password will not be useful in 24 hours.""".format(recipient, password))

            message['Subject']  = "Your password to use MagshiProject"
            message['From']     = sender
            message['To']       = recipient
            s                   = smtplib.SMTP("smtp.google.com", 587)
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login("Username", "Password")
            s.sendmail(me, [you], msg.as_string())
            s.quit()
            print "Message has been sent successfully."
        except Exception as e:
            print "Something went wrong, Please try again later."
            print "Error Message: '{0}'.".format(str(e))
            print "Error type: '{0}'.".format(str(type(e)))
    sendAnEmail()

The error is the following:

Something went wrong, Please try again later.
Error message: '[Errno 11001] getaddrinfo failed'.
Error type: '<class 'socket.gaierror'>'.

What can I do in oder to solve this?

Thank you in advance, Iliya

There are a few issues with your code that seem to indicate that this is a bit of a copy/paste job, but hopefully we can talk through this to help you out.

Server Address

You'll notice that you've used the following code to connect to the SMTP server

s = smtplib.SMTP("smtp.google.com", 587)

However, a quick Google search of "Gmail SMTP" shows us all the SMTP settings for Gmail , including the address: "smtp.gmail.com" . So we change this to

s = smtplib.SMTP("smtp.gmail.com", 587)

Incorrect/Missing Variables

Additionally, there is one other small bug

s.sendmail(me, [you], msg.as_string())

Obviously me and [you] are not defined, so based on your other variables, me should be the sender of the email and [you] should be the recipient , so we will replace those values with your existing variables. You also have no variable msg , so in this case it should probably be message.as_string() .

Also, the "Username" that we are using with s.login("Username","Password") would presumably be the same person who is sending the email, so we will replace this with sender .

So here is the code in its corrected form

#Mail Module
try:
    import smtplib
    import sys
    from email.mime.text import MIMEText
except ImportError:
    print "Error importing necessary modules into the project, Please contact MagshiProject staff"
else:
    def sendAnEmail():
        try:
            sender      = "magshiproject@gmail.com"
            recipient   = str(sys.argv[1])
            password    = str(sys.argv[2])
            message     = MIMEText("""From: From Magshimim Project <magshiproject@gmail.com>
                            To: To User <'{0}'>
                            Subject: Your password to further use MagshiProject Program

                            Your password is: '{1}'
                            Please copy and paste it from here to the window requesting this password in order to proceed.
                            This password will not be useful in 24 hours.""".format(recipient, password))

            message['Subject']  = "Your password to use MagshiProject"
            message['From']     = sender
            message['To']       = recipient
            s                   = smtplib.SMTP("smtp.gmail.com", 587)
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(sender, "Password")
            s.sendmail(sender, recipient, message.as_string())
            s.quit()
            print "Message has been sent successfully."
        except Exception as e:
            print "Something went wrong, Please try again later."
            print "Error Message: '{0}'.".format(str(e))
            print "Error type: '{0}'.".format(str(type(e)))
    sendAnEmail()

This will work assuming that you replace "Username" and "Password" with actual values and you call the program with arguments as follows (assume file is called sendmail.py )

python sendmail.py "someone@somewhere.com" "password"

EDIT: Getting password for sender

To make this script even more polished, you can prompt for the sender password using the getpass module. Add the following import

import getpass

And then changed "Password" in s.login(sender, "Password") to

s.login(sender,getpass.getpass("Please enter your password for %s: " % sender))

And you will be prompted for the gmail password for sender

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