使用Python Flask-mail发送邮件

来源:互联网 发布:头皮里面长痘痘 知乎 编辑:程序博客网 时间:2024/06/04 18:22
# -*-coding:utf-8 -*-'''Created on 2017年5月25日@author: Administrator'''from flask import Flaskfrom flask_mail import Mail, Messageimport osapp = Flask(__name__)###下面是配置设置app.config.update(    DEBUG = True,    MAIL_SERVER='smtp.163.com',#以163邮箱为例    MAIL_PROT=25,##端口号    MAIL_USE_TLS = True,    MAIL_USE_SSL = False,    MAIL_USERNAME = '你的发件邮箱地址',    MAIL_PASSWORD = '邮箱密码(不是登录邮箱的密码,是设置pop3等协议的密码)',    MAIL_DEBUG = True)mail = Mail(app)@app.route('/')def index():    # sender 发送方,recipients邮件接收方列表    msg = Message("发一张 图片给你看看我的头像,在附件中",sender='******@163.com', recipients=['*****@qq.com'])# msg.body 邮件正文    msg.body = "给你发一封测试邮件,用代码写的"# msg.attach 邮件附件添加# msg.attach("文件名", "类型", 读取文件)#例(1)以附件的形式发一张图片#     with app.open_resource("F:\\1.jpg","rb") as fp:#         msg.attach("image.jpg", "image/jpg", fp.read())#例(2)以附件的形式发Word文档#     with app.open_resource("F:\\new.docx","rb") as fp:#         msg.attach("pic.docx", "txt/docx", fp.read())#例(3)以附件的形式发.rar压缩文件    with app.open_resource("F:\\new.rar","rb") as fp:        msg.attach("pic.rar", "zip/rar", fp.read())    try:        mail.send(msg)    except Exception,e:        print "send error"+str(e)        return "send error"+str(e)    else:        return "Sent successfully"if __name__ == "__main__":    app.run()###注意如果163服务器将你的邮件识别为垃圾邮件,请修改msg =Message("修改这里的内容",sender="***@***",recipents="***@***")或者msg.body()中的字符串内容或者###电脑在联网的状态下,打开浏览器窗口,在地址栏中输入:127.0.0.1:5000 ,然后回车键就完成了
原创粉丝点击