gpt4 book ai didi

python - 使用 Python 发送电子邮件问题

转载 作者:行者123 更新时间:2023-12-01 05:27:44 25 4
gpt4 key购买 nike

我有这段代码,但我似乎无法让它工作。当我运行它时,除非我手动终止脚本,否则脚本不会在空闲状态下完成。我仔细检查并重写了代码几次,但没有成功。

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

最佳答案

不确定您为什么使用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)

关于python - 使用 Python 发送电子邮件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21008030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com