python email发送脚本gmail

时间:2014-08-12 11:58:07

标签: python email

我正在制作一个简单的脚本,用于通过python 2.7.5中的gmail帐户发送邮件。在发送邮件之前,我想检查用户是否通过gmail smtp成功登录...这是我的代码:

#!/usr/bin/python
import smtplib
user = raw_input("Enter Your email address: ")
password= raw_input("Enter your email password: ")
receipt = raw_input("Enter Receipt email address: ")
subject = raw_input ("Subject: ")
msg = raw_input("Message: ")
message =  """\From: %s\nTo: %s\nSubject: %s\n\n%s
            """ % (user, ", ".join(receipt), subject, msg)
smtp_host = 'smtp.gmail.com'
smtp_port = 587
session = smtplib.SMTP()
session.connect(smtp_host, smtp_port)
session.ehlo()
session.starttls()
session.ehlo
print "Connecting to the server....."
try:
    session.login(user, password) 
    if (session.verify(True)):
        print "Connected to the server. Now sending mail...."
        session.sendmail(user, receipt, message)
        session.quit()
        print "Mail have been sent successfully.....!"
except smtplib.SMTPAuthenticationError:
    print "Can not connected to the Server...!"

print "Simple mail Test"

但是当我运行它时,它会给出“无法连接到服务器”。任何人都可以帮我解决我的错误吗?

1 个答案:

答案 0 :(得分:1)

你忘记了几件事。收据必须是列表,验证方法将用户电子邮件作为参数。这里的代码有一些改进:

#!/usr/bin/python
import smtplib
receipt,cc_list=[],[]
user = raw_input("Enter Your email address: ")
password= raw_input("Enter your email password: ")
receipt.append(raw_input("Enter Receipt email address: "))
subject = raw_input ("Subject: ")
message = raw_input("Message: ")

header  = 'From: %s\n' % user
header += 'To: %s\n' % ','.join(receipt)
header += 'Cc: %s\n' % ','.join(cc_list)
header += 'Subject: %s\n\n' % subject
message = header + message

smtp_host = 'smtp.gmail.com'
smtp_port = 587
session = smtplib.SMTP()
session.connect(smtp_host, smtp_port)
session.ehlo()
session.starttls()
session.ehlo

print "Connecting to the server....."
try:
    session.login(user, password) 
    if (session.verify(user)):
        print "Connected to the server. Now sending mail...."
        session.sendmail(user, receipt, message)
        session.quit()
        print "Mail have been sent successfully.....!"
except smtplib.SMTPAuthenticationError:
    print "Can not connected to the Server...!"

print "Simple mail Test"