我有这个代码,我似乎无法让它工作。当我运行它时,脚本没有在IDLE中完成,除非我手动杀死它。我已经看了一遍并重写了几次代码,但没有运气。
import smtplib
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'abc@gmail.com'
password = '123'
recipient = 'cba@gmail.com'
subject = 'Test Results'
body = """** AUTOMATED EMAIL ** \r\n Following are
the test results: \r\n"""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient]
headers = "\r\n".join(headers)
try:
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo()
session.login(sender, password)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
except smtplib.SMTPException:
print "Error: Unable to send email."
session.quit()
答案 0 :(得分:2)
不确定您使用ehlo
的原因;与流行的观点相反,只要你正确设置标题,它实际上并不需要。这是一个经过测试和运行的脚本 - 它适用于* nix和OSX。由于您使用的是Windows,我们需要进一步排查。
import smtplib, sys
def notify(fromname, fromemail, toname, toemail, subject, body, password):
fromaddr = fromname+" <"+fromemail+">"
toaddrs = [toname+" <"+toemail+">"]
msg = "From: "+fromaddr+"\nTo: "+toemail+"\nMIME-Version: 1.0\nContent-type: text/plain\nSubject: "+subject+"\n"+body
# Credentials (if needed)
username = fromemail
password = password
# The actual mail send
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print "success"
except smtplib.SMTPException:
print "failure"
fromname = "Your Name"
fromemail = "yourgmailaccount@gmail.com"
toname = "Recipient"
toemail = "recipient@other.com"
subject = "Test Mail"
body = "Body....."
notify(fromname, fromemail, toname, toemail, subject, body, password)