繁体   English   中英

通过本地Exim MTA用python发送电子邮件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM