我正在运行一个程序。当该程序得到结果时,它将使用以下功能向我发送电子邮件:
def send_email(message):
import smtplib
gmail_user = OMITTED
gmail_pwd = OMITTED
FROM = OMITTED
TO = OMITTED #must be a list
try:
#server = smtplib.SMTP(SERVER)
server = smtplib.SMTP("smtp.gmail.com", 587) #or port 465 doesn't seem to work!
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
#server.quit()
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
Run Code Online (Sandbox Code Playgroud)
免责声明:我在Stack Overflow的某处找到了此代码。不是我的 我删去了某些部分,因为它们似乎没有特殊意义。
有时我的代码会得到很多结果,并且我在不到20秒的时间内收到了150多种不同的电子邮件。
如何修改上面的函数,以便程序在同一线程中将所有结果发送给我?
如果您不明白我的意思,我希望我的收件箱看起来像这样:
sender@gmail.com(150) ...
... (other emails from other senders)
Run Code Online (Sandbox Code Playgroud)
代替:
sender@gmail.com ...
sender@gmail.com ...
sender@gmail.com ...
sender@gmail.com ...
sender@gmail.com ...
...
sender@gmail.com ...
... (other emails from other senders)
Run Code Online (Sandbox Code Playgroud)
编辑
为了解决该问题,我要做的就是重新插入我先前删除的代码部分。全部功能是这一功能:
def send_email(TEXT):
import smtplib
gmail_user = OMITTED
gmail_pwd = OMITTED
FROM = OMITTED
TO = OMITTED #must be a list
SUBJECT = "Big brother candidate"
#TEXT = "Testing sending mail using gmail servers"
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
#server = smtplib.SMTP(SERVER)
server = smtplib.SMTP("smtp.gmail.com", 587) #or port 465 doesn't seem to work!
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
#server.quit()
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
Run Code Online (Sandbox Code Playgroud)
这是一个古老的问题,但是我不得不回答这个问题,因为有一种方法可以执行OP想要的操作。您可以通过在邮件中添加标题,并在发送另一封电子邮件时引用它们来实现。例如
from email.utils import make_msgid
my_id = make_msgid()
#Build your email as you normally do, and add ID as a message header
message = MIMEMultipart()
message["Message-ID"] = my_id
message["Subject"] = "test"
message["From"] = from_email
# ...etc and send your email using smtp.sendmail
# On the reply (or when sending another email), add the following headers
message["In-Reply-To"] = my_id
message["References"] = my_id
# ...send your email using smtp.sendmail
Run Code Online (Sandbox Code Playgroud)
当您检查邮件客户端时,您会看到后一封电子邮件将作为对前一封电子邮件的答复而发布,从而创建了通常在常用电子邮件客户端(Gmail,收件箱,Outlook,Yahoo等)中看到的线程。