使用Python Flask-mail發送郵件

# -*-coding:utf-8 -*-
'''
Created on 2017年5月25日

@author: Administrator
'''
from flask import Flask
from flask_mail import Mail, Message
import os

app = 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 ,然後回車鍵就完成了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章