要安全地保存SMTP的Gmail账户凭据,你可以使用以下解决方法:
import os
import smtplib
# 从环境变量中获取Gmail账户的用户名和密码
gmail_username = os.environ.get('GMAIL_USERNAME')
gmail_password = os.environ.get('GMAIL_PASSWORD')
# 使用SMTP发送邮件
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(gmail_username, gmail_password)
# 发送邮件的代码...
然后,你可以使用export
命令将环境变量设置为你的账户凭据:
export GMAIL_USERNAME=your_username
export GMAIL_PASSWORD=your_password
config.ini
),将Gmail账户的用户名和密码存储在其中,并在代码中读取这些配置信息。确保将配置文件添加到.gitignore
文件中,以防止将敏感信息提交到版本控制系统中。import configparser
import smtplib
# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')
# 获取Gmail账户的用户名和密码
gmail_username = config.get('Gmail', 'username')
gmail_password = config.get('Gmail', 'password')
# 使用SMTP发送邮件
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(gmail_username, gmail_password)
# 发送邮件的代码...
在config.ini
文件中,添加以下内容:
[Gmail]
username = your_username
password = your_password
import base64
import smtplib
# 加密函数
def encrypt(text):
# 加密逻辑...
encrypted_text = base64.b64encode(text.encode()).decode()
return encrypted_text
# 解密函数
def decrypt(encrypted_text):
# 解密逻辑...
decrypted_text = base64.b64decode(encrypted_text.encode()).decode()
return decrypted_text
# 获取加密后的Gmail账户的用户名和密码
encrypted_username = 'encrypted_username'
encrypted_password = 'encrypted_password'
gmail_username = decrypt(encrypted_username)
gmail_password = decrypt(encrypted_password)
# 使用SMTP发送邮件
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(gmail_username, gmail_password)
# 发送邮件的代码...
请注意,上述示例只是提供了一些基本的方法,实际上,要安全地保存账户凭据,需要更复杂的加密和解密机制,并确保密钥的安全性。