通过本地Exim MTA发送电子邮件到python
问题描述:
我试图在我的Arch Linux VPS上创建一个自动化系统,它会将每月的HTML格式的报告发送到我的电子邮件。我决定使用python作为编程语言,但是我发现自己陷入了困境。通过本地Exim MTA发送电子邮件到python
在下面的代码中,您会发现我使用SMTPlib来构建和发送消息。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def py_mail(SUBJECT, BODY, TO, FROM):
""""With this function we send out our HTML email"""
# Create message container - the correct MIME type is multipart/alternative here!
MESSAGE = MIMEMultipart('alternative')
MESSAGE['subject'] = SUBJECT
MESSAGE['To'] = TO
MESSAGE['From'] = FROM
MESSAGE.preamble = """"Your reader does not support the report format. Please visit
us <a href="https://my-website.nl">online</a>!"""
# Record the MIME type text/html
HTML_BODY = MIMEText(BODY, 'html')
# Attach parts into message container
MESSAGE.attach(HTML_BODY)
# Create SMTP object
server = smtplib.SMTP(host='localhost', port=587)
# Print debugging output when testing
if __name__ == '__main__':
server.set_debuglevel(1)
# The actual sending of the email
try:
server.starttls()
server.sendmail(FROM, [TO], MESSAGE.as_string())
server.quit()
except smtplib.SMTPException as error:
print("Error: unable to send mail : {err}".format(err=error))
if __name__ == '__main__':
"""Executes if the script is run as main script (for testing purposes)"""
email_content = """"
<head>
<link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300" rel="stylesheet">
<meta charset="UTF-8">
<title>TestMail</title>
<style>
h1 {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
font-family: "Open Sans Condensed", sans-serif;
font-size: 3em;
}
</style>
</head>
<body>
<h1>'tis but a scratch</h1>
</body>
"""
TO = '[email protected]'
FROM = '[email protected]'
py_mail("Test email onderwerp", email_content, TO, FROM)
但是,一旦我运行该脚本,我得到以下错误:
ConnectionRefusedError: [Errno 111] Connection refused
我有进出口运行作为本地MTA只送我的服务器上。我没有问题通过命令行发送电子邮件。一旦我尝试用Python连接它,问题才会开始发生。
如果任何人都可以帮助我,那就太棒了。在此先感谢
答
你真的有本地主机端口587上运行的SMTP服务器?尝试端口25 - 这是SMTP的标准端口。 587适用于SSL/TLS,但您必须为此配置SMTP。
如果您确定它必须真正是端口587 - 请检查防火墙设置。
所以我将它设置为25端口,但不幸的是仍然是同样的错误。为了测试,我也很快禁用了防火墙,然后重新启用它。仍然没有变化。 –