Python 高级应用技巧大揭秘
1. 用 Python 发送邮件
想要从 Python 程序发送邮件,可使用 Python 的 Simple Mail Transfer Protocol (SMTP) 库。不过,在代码中使用用户名和密码时要格外小心,尤其是将代码上传到互联网时,很容易不小心把密码也上传了。
以 Google 的 Gmail 为例,Google 有应用专用密码的概念,这让访问更安全。获取此密码的步骤如下:
1. 从浏览器正常登录 Google,访问 https://myaccount.google.com/。
2. 点击左侧导航栏中的“Security”。
3. 在“Signing in to Google”部分,选择“App Passwords”。
4. 在“Select App”下拉列表中,选择“email”。
5. 在“Select Device”下拉列表中,选择“Other”,并为设备(如树莓派)命名,例如“Raspberry Pi Python”。
6. 点击“Generate”按钮,会生成一个密码,将其复制并粘贴到以下 Python 程序(ch_07_gmail.py)中:
import smtplib
GMAIL_USER = 'your email address'
GMAIL_PASS = 'your password'
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
def send_email(recipient, subject, text):
smtpserver
Python高级技巧实战指南
超级会员免费看
订阅专栏 解锁全文
684

被折叠的 条评论
为什么被折叠?



