编辑方式如先前不清楚。

如果我在下面的代码中运行而没有在while循环中运行,则它将完美运行。一旦将其放入while循环中(我需要将其作为较大的脚本的一部分),由于某种原因,它会丢失邮件的主题并将其发送为空白。其他一切都很好-电子邮件的收件人,发件人和正文都可以。它只是出于某种原因而放弃了主题。有任何想法吗?

import smtplib
import time


while True :
 newnumber = "200"
 oldnumber = "100"
 SERVER = "mail"
 FROM = "mail"
 TO = "mail"
 SUBJECT = "Blah blah blah blah blah"
 BODY = """Blah blah blah blah blah.\n\n
 The new number is: %s\n
 The old number is: %s\n\n
 Blah blah blah blah blah.\n\n
 Blah blah blah blah blah\n
 Blah.""" % (newnumber,oldnumber)

 message = """\
 From: %s
 To: %s
 Subject: %s

 %s
 """ % (FROM, TO, SUBJECT, BODY)

 if oldnumber < newnumber:
        server = smtplib.SMTP(SERVER)
        server.sendmail(FROM, TO, message)
        server.quit()
        time.sleep(60)

最佳答案

在这里查看python文档https://docs.python.org/3.4/library/email-examples.html#email-examples

这是发送多部分消息的示例

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText    SERVER = "localhost"

SERVER = "localhost"
FROM = "me"
TO = "you"
SUBJECT = "Test"
BODY = "Test"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = FROM
msg['To'] = TO
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(BODY, 'text')
# part2 = MIMEText(HTML_BODY, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
# msg.attach(part2)

# Send the message via SMTP server.
s = smtplib.SMTP(SERVER)
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
failed_addresses = s.sendmail(mailFrom, mailTo, msg.as_string())

关于python - smtplib-发送但在while循环中缩进时没有主题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26013594/

10-09 17:10