一、什麼是POP3、SMTP和IMAP?
二、開啓郵箱的SMTP服務
以常用的網易郵箱爲例(其他同理):登錄後進入常規設置
- 選擇POP3/SMTP/IMAP:開啓如下兩條服務,並注意到這裏提示使用的是授權碼登錄第三方客戶端,而非郵箱密碼(有些郵箱使用的是密碼而非授權碼)。
- 頁面的最下方還有一個提示內容如下,這個也會在後面用到,有兩個重要信息:
- SMTP的服務器:smtp.163.com
- 安全支持:POP3/SMTP/IMAP服務是全部支持SSL連接的
- 設置中選擇 客戶端授權密碼 這一欄並選擇開啓,並記住這個授權碼,開啓後如下:
- 網易郵箱的相關服務器信息:
三、Python Flask框架發送郵件
- 安裝依賴包:flask_mail
pip install flask_mail
- 這裏假設一種情況,比如一般在註冊一個網站時,會給用戶發送驗證郵件,這時我們用瀏覽器訪問這個接口(http://localhost:5000/register)時就會發送對應的郵件到用戶郵箱(當然省略了很多如生成驗證碼等內容)。
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
class Config(object):
DEBUG = True
MAIL_SERVER = 'smtp.163.com' # 郵件服務器地址
MAIL_PORT = '465' # SSL協議端口號
MAIL_USE_SSL = True # 使用SSL加密
MAIL_USERNAME = '[email protected]' # 郵箱
MAIL_PASSWORD = 'xxxxxxxx' # 授權碼(某些郵箱是直接使用密碼)
app.config.from_object(Config)
mail = Mail(app)
@app.route('/register', strict_slashes = False)
def register():
msg = Message('填寫郵件標題', sender='[email protected]', recipients=['[email protected]', '[email protected]'])
msg.body = '郵件內容'
mail.send(msg)
return '郵件發送成功!'
if __name__ == '__main__':
app.run(host = '0.0.0.0',port = 5000)