我试图在我的Arch Linux VPS上创建一个自动系统,该系统会将每月HTML格式的报告发送到我的电子邮箱。我决定使用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 = 'to-email@website.com'
FROM = 'from-email@website.com'
py_mail("Test email onderwerp", email_content, TO, FROM)
但是一旦我运行脚本,我就会收到以下错误:
ConnectionRefusedError:[Errno 111]拒绝连接
我在我的服务器上运行Exim作为本地的仅发送MTA。通过命令行发送电子邮件没有问题。只有在我尝试使用Python连接问题时才会出现问题。
如果有人能帮助我,那就太棒了。提前致谢
答案 0 :(得分:-1)
您是否真的在localhost端口587上运行SMTP服务器?尝试端口25 - 它是SMTP的标准端口。 587适用于SSL / TLS,但您必须为此配置SMTP。
如果您确定它必须真的是端口587 - 请检查防火墙设置。