2017-05-30 81 views
1

我試圖在我的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連接它,問題纔會開始發生。

如果任何人都可以幫助我,那就太棒了。在此先感謝

回答

-1

你真的有本地主機端口587上運行的SMTP服務器?嘗試端口25 - 這是SMTP的標準端口。 587適用於SSL/TLS,但您必須爲此配置SMTP。

如果您確定它必須真正是端口587 - 請檢查防火牆設置。

+0

所以我將它設置爲25端口,但不幸的是仍然是同樣的錯誤。爲了測試,我也很快禁用了防火牆,然後重新啓用它。仍然沒有變化。 –