2017-11-04 34 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视图中。