2017-11-04 35 views
0

這是我的代碼使用帶附件發送電子郵件(sample.txt的 - 測試文件),發送郵件在Python 3.X

,但我沒有收到任何郵件的和沒有錯誤的被拋出

我試圖發送沒有附件的郵件,它工作...

我在做什麼錯誤的附件部分?

def sendmail(): 
    try: 
     #... 
     msg.body = "Hello Flask message sent from Flask-Mail" 
     with app.open_resource("sample.txt") as fp: 
      msg.attach("sample.txt", "text/plain", fp.read()) 
     mail.send(msg) 
    except Exception as e: 
     raise e 
return "Check Your Inbox !!!" 
+0

我認爲你的代碼看起來很好。嘗試移除「text/plain」,例如:msg.attach(「sample.txt」,fp.read())'或嘗試文件的完整路徑。 –

回答

0

下面的這段代碼適合我。在這個例子中我使用了gmail的SMTP服務器。 運行該程序首先

from flask import Flask 
from flask_mail import Mail 
from flask_mail import Message 

# Configure these 
sender = '[email protected]' 
recip = '[email protected]' 
image = 'example.png' 
mailpass = 'aabbcc' 

app = Flask(__name__) 
mail = Mail(app) 

app.extensions['mail'].server = 'smtp.gmail.com' 
app.extensions['mail'].port = 587 
app.extensions['mail'].use_tls = True 
app.extensions['mail'].username = sender 
app.extensions['mail'].password = mailpass 


@app.route('/') 
def sendmail(): 
    msg = Message('This is a test email', 
        sender=sender, 
        recipients=[recip]) 

    with app.open_resource(image) as f: 
     msg.attach('image.png', 'image/png', f.read()) 
    mail.send(msg) 
    return 'mail sent' 
app.run('localhost', 8888) 

然後觸發REST調用:

curl localhost:8888/ 

我不只是因爲我在PyCharm調試它從燒瓶運行程序。通過完成以上所有操作,圖片出現在我的gmail視圖中。