我正在尝试使用Pythion smtp库发送电子邮件。我收到了以下代码,但当我收到电子邮件时,它没有"To"
,"Subject"
和"Body"
内容,因为它们缺失了。我认为构造message
字符串的方式有问题。
import smtplib
import socket
FROM = "from@host.com"
TO = ["to@host.com"]
def send_email():
hostname = socket.getfqdn()
text = "Hello"
subject = "Error on %s " % (hostname)
print subject
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), subject, text)
smtp_server = ""
if ".dev" not in hostname:
smtp_server = "abc.host.com"
else:
smtp_server = "pqr.host.com"
# Send the mail
server = smtplib.SMTP(smtp_server)
server.sendmail(FROM, TO, message)
server.quit()
send_email()
但是当我使用完全相同的下面代码时,它可以正常工作而没有任何问题,所以当我把所有东西都放在一个方法中时,我确信上面的代码有问题。我认为缩进会导致消息字符串被构造的方式或其他我无法弄清楚的问题。
import smtplib
import socket
SERVER = "abc.host.com"
FROM = "from@host.com"
TO = ["to@host.com"]
SUBJECT = "Test! %s " % (socket.getfqdn())
TEXT = "Testing."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join( TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
这是我在第一段代码中看到的内容。如果仔细观察,每个标签前面都有很多空格,而第二个代码打印的空格则是:
From: from@host.com
To: to@host.com
Subject: Error on machineA
Hello
这是我在第二段代码中看到的:
From: from@host.com
To: to@host.com
Subject: Test! machineA
Testing.
当我将它放入方法时,如何在第一个代码中修复此问题?
更新
我尝试使用下面的代码,但它在print message
上给出了关于缩进错误的错误。
import smtplib
import socket
FROM = "from@host.com"
TO = ["to@host.com"]
def send_email():
hostname = socket.getfqdn()
text = "Hello"
subject = "Error on %s " % (hostname)
print subject
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), subject, text)
print message
smtp_server = ""
if ".dev" not in hostname:
smtp_server = "abc.host.com"
else:
smtp_server = "pqr.host.com"
# Send the mail
server = smtplib.SMTP(smtp_server)
server.sendmail(FROM, TO, message)
server.quit()
send_email()
答案 0 :(得分:1)
您可以删除缩进:
def send_email():
# stuff ...
# Prepare actual message
message = """\
From: %s
- other stuff...
""" % (FROM, ", ".join(TO), subject, text)
smtp_server = ""
# more stuff...
server.sendmail(FROM, TO, message)
server.quit()
另外,不确定你需要反斜杠吗?
message = ''' < == no backslash
stuff
'''
答案 1 :(得分:0)
使用stdlib email
程序包帮助您将邮件构建为正确的SMTP有效负载(标头,编码,部件......)。 https://docs.python.org/3/library/email.html#module-email
标准文档或stackoverflow中有大量示例。