我正在尝试在我的 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 连接到它时才开始出现。
如果有人可以帮助我,那就太棒了。提前致谢