发送电子邮件与Python问题 [英] Sending an Email with Python Issue
本文介绍了发送电子邮件与Python问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码,我似乎无法让它工作。当我运行它,该脚本不会在IDLE完成,除非我手动杀死它。我已经看了一遍,重写了代码几次,没有运气。
I have this code and I cannot seem to get it to work. When I run it, the script doesn't finish in IDLE unless I kill it manually. I have looked all over and rewritten the code a few times, and no luck.
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()
推荐答案
p>不知道你为什么使用 ehlo
;与流行观点相反,只要您正确设置标题,实际上并不是必需的。这是一个经过测试和工作的脚本 - 它适用于* nix和OSX。由于您使用的是Windows,因此我们需要进一步解决问题。
Not sure why you're using ehlo
; contrary to popular opinion, it's not actually required so long as you set the headers correctly. Here's a tested and working script -- it works on *nix and OSX. Since you're using Windows though, we need to troubleshoot further.
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)
这篇关于发送电子邮件与Python问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文