通过python通过gmail发送电子邮件时出错

时间:2014-07-11 13:43:04

标签: python email

您好!

我正在尝试在Python中执行一个程序,该程序将在命令行参数中接收电子邮件地址和一些短语,程序会将短语(带有一些背景信息)发送到提供的电子邮件地址。

代码如下:

#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()

错误如下:

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

我可以用什么来解决这个问题?

提前谢谢你, Iliya

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题似乎表明这是一个复制/粘贴工作,但希望我们可以通过这个来帮助您解决问题。

服务器地址

您会注意到您已使用以下代码连接到SMTP服务器

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

然而,快速Google搜索&#34; Gmail SMTP&#34;向我们显示all the SMTP settings for Gmail,包括地址:"smtp.gmail.com"。所以我们将其更改为

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

不正确/缺少变量

此外,还有一个小错误

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

显然me[you]未定义,因此根据您的其他变量,me应该是电子邮件的sender[you]应该是recipient,我们将用现有变量替换这些值。您也没有变量msg,因此在这种情况下它应该是message.as_string()

此外,&#34;用户名&#34;我们与s.login("Username","Password")一起使用的人可能就是发送电子邮件的人,因此我们会将其替换为sender

所以这里是修正后的代码

#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()

这将假设您将"Username""Password"替换为实际值,并使用如下参数调用程序(假设文件名为sendmail.py

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

编辑:获取sender

的密码

为了使此脚本更加完善,您可以使用getpass模块提示sender密码。添加以下导入

import getpass

然后将"Password"中的s.login(sender, "Password")更改为

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

系统将提示您输入sender

的Gmail密码