2016-12-02 60 views
0

我想寫一個模塊作爲我的代碼發送電子郵件的一部分。我有這樣的代碼,它不會拋出任何異常,但它不會像我期望的那樣提供電子郵件。任何人都可以幫我指出這個代碼可能存在的問題嗎?提前致謝!使用Python發送電子郵件與smtp

""" before sending email with this code 
    I start smtp server: 
    python -m smtpd -n -c DebuggingServer localhost:1025 
    """ 
    #!/usr/bin/python -tt 

    from email.mime.text import MIMEText 
    from datetime import date 
    import smtplib 

    SMTP_SERVER = "localhost" 
    SMTP_PORT = 1025 

    EMAIL_TO = ["[email protected]"] 
    EMAIL_FROM = "[email protected]" 
    EMAIL_SUBJECT = "*Email Test*" 

    DATE_FORMAT = "%d/%m/%Y" 
    EMAIL_SPACE = ", " 

    DATA='Test email sending feature in Python' 

    def send_email(): 
     msg = MIMEText(DATA) 
     msg['Subject'] = EMAIL_SUBJECT + " %s" %(date.today().strftime(DATE_FORMAT)) 
     msg['To'] = EMAIL_SPACE.join(EMAIL_TO) 
     msg['From'] = EMAIL_FROM 
     mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) 
     mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string()) 
     mail.quit() 

    if __name__=='__main__': 
     try: 
      send_email() 
     except Exception as e: 
      import traceback;traceback.print_exc() 

感謝

+0

縮進有點奇怪。這只是帖子還是原版中還有別的東西? – Javier

+0

@Javier我搞砸了縮進,而複製+粘貼,現在修復它 – user1596115

回答

0

嗨,你可以刪除除了嘗試,並再次運行呢?

因爲您使用的是Gmail。你可以試試這個

import smtplib 

server = smtplib.SMTP('smtp.gmail.com', 587) 
server.starttls() 
server.login("[email protected]", "your-password-here") 

msg = "YOUR MESSAGE!" 
server.sendmail("[email protected]", "[email protected]", msg) 
server.quit() 
+0

這也行不通! – user1596115

+0

仍然沒有錯誤?並沒有發送電子郵件? –

+0

沒有錯誤或電子郵件 – user1596115