- Web2py 教程
- Web2py - 首頁
- Web2py - 簡介
- Web2py - Python 語言
- Web2py - 框架概述
- Web2py - 核心
- Web2py - 檢視
- Web2py - 資料庫抽象層
- Web2py - 表單與驗證器
- Web2py - 電子郵件與簡訊
- Web2py - 訪問控制
- Web2py - 服務
- Web2py - 新增 Ajax 效果
- Web2py - 元件
- Web2py - 部署
- Web2py - 安全性
- Web2py 有用資源
- Web2py - 快速指南
- Web2py - 有用資源
- Web2py - 討論
Web2py - 電子郵件與簡訊
web2py 包含向用戶傳送電子郵件和簡訊的功能。它使用庫來發送電子郵件和簡訊。
設定電子郵件
內建類,即gluon.tools.Mail類用於在web2py框架中傳送電子郵件。郵件傳送器可以使用此類定義。
from gluon.tools import Mail mail = Mail() mail.settings.server = 'smtp.example.com:25' mail.settings.sender = 'abc@example.com' mail.settings.login = 'username:password'
每次傳送電子郵件時,都會對上述示例中提到的發件人電子郵件及其密碼進行身份驗證。
如果使用者需要進行實驗或用於某些除錯目的,可以使用以下程式碼實現。
mail.settings.server = 'logging'
現在,所有電子郵件都不會發送,而是會記錄在控制檯中。
傳送電子郵件
一旦我們使用郵件物件設定了電子郵件的配置設定,就可以向許多使用者傳送電子郵件。
mail.send()的完整語法如下:
send(
to, subject = 'Abc',
message = 'None', attachments = [],
cc = [], bcc = [], reply_to = [],
sender = None, encoding = 'utf-8',
raw = True, headers = {}
)
mail.send()的實現如下所示。
mail.send( to = ['sender@example.com'], subject = 'hello', reply_to = 'abc@example.com', message = 'Hello ! How are you?' )
Mail根據郵件伺服器的響應返回一個布林表示式,表示郵件是否已由終端使用者接收。如果成功向用戶傳送電子郵件,則返回True。
屬性to、cc和bcc包含打算傳送郵件的有效電子郵件地址列表。
傳送簡訊
在web2py框架中,傳送簡訊的實現與傳送電子郵件不同,因為它需要第三方服務才能將訊息轉發給接收者。第三方服務並非免費服務,並且顯然會因地理區域(國家/地區而異)而異。
web2py 使用一個模組來幫助傳送簡訊,過程如下:
from gluon.contrib.sms_utils
import SMSCODES, sms_email
email = sms_email('1 (111) 111-1111','T-Mobile USA (abc)')
mail.send(to = email, subject = 'test', message = 'test')
在上面的示例中,SMSCODES是由web2py維護的字典,它將主要電話公司的名稱對映到電子郵件地址字尾。
電話公司通常將來自第三方服務的電子郵件視為垃圾郵件。更好的方法是電話公司自己轉發簡訊。每個電話公司在其儲存中為每個手機號碼包含一個唯一的電子郵件地址,並且可以將簡訊直接傳送到該電子郵件。
在上面的示例中:
sms_email函式接受一個電話號碼(作為字串),它返回電話的電子郵件地址。
腳手架應用程式包含多個檔案。其中一個是models/db.py,它匯入了四個。
來自gluon.tools的類也包含郵件庫,並定義了各種全域性物件。
腳手架應用程式還定義了auth物件所需的表,例如db.auth_user。預設腳手架應用程式旨在最大限度地減少檔案數量,而不是模組化。特別是,模型檔案db.py包含配置,在生產環境中,最好將其儲存在單獨的檔案中。
在這裡,我們建議建立一個配置檔案:
from gluon.storage import Storage
settings = Storage()
settings.production = False
if
settings.production:
settings.db_uri = 'sqlite://production.sqlite'
settings.migrate = False
else:
settings.db_uri = 'sqlite://development.sqlite'
settings.migrate = True
settings.title = request.
settings.subtitle = 'write something here'
settings.author = 'you'
settings.author_email = 'you@example.come'
settings.keywords = ''
settings.description = ''
settings.layout_theme = 'Default'
settings.security_key = 'a098c897-724b-4e05-b2d8-8ee993385ae6'
settings.email_server = 'localhost'
settings.email_sender = 'you@example.com'
settings.email_login = ''
settings.login_method = 'local'
settings.login_config = ''