[英]Send e-mail in python via local Exim MTA
我試圖在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連接到問題時,問題才開始出現。
如果有人可以幫助我,那就太好了。 提前致謝
您真的在本地主機端口587上運行SMTP服務器嗎? 嘗試端口25-這是SMTP的標准端口。 587適用於SSL / TLS,但您必須為此配置SMTP。
如果確定確實是587端口,請檢查防火牆設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.