我查看了过去的线程,但据我所知,没有一个解决方案对我有用。我的代码如下:
import smtplib
import config
EMAIL_ADDRESS = '***'
EMAIL_PASSWORD = '***'
if re.search(pattern, body) is None:
def send_email(subject, msg):
try:
server = smtplib.SMTP('smtp-mail.outlook.com:587')
server.ehlo()
server.starttls()
server.login(config.EMAIL_ADDRESS, config.EMAIL.PASSWORD)
message = 'Subject: {}\n\n{}'.format(subject, msg)
server.sendmail(config.EMAIL_ADDRESS, '***@gmail.com', message)
server.quit()
print("email sent ツ")
您正在观看的教程告诉您创建一个名为 的文件,并将和config.py
的定义放入其中。但是,您似乎将这些定义与其他所有内容放在同一个脚本中。EMAIL_ADDRESS
EMAIL_PASSWORD
这没关系,但如果你要这样做,你不需要放在import config
代码的顶部。config.
每次引用变量时,您也不需要在变量名称之前放置它们。
工作代码如下所示:
import smtplib
EMAIL_ADDRESS = "***"
EMAIL_ADDRESS2 = "***"
EMAIL_PASSWORD = "***"
def send_email(subject, msg):
try:
server = smtplib.SMTP("smtp-mail.outlook.com:587")
server.ehlo()
server.starttls()
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
message = f"Subject: {subject}\n\n{msg}"
server.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS2, message)
server.quit()
print("email sent ツ")
except:
print("Email failed to send :(")
但是,将密码等敏感信息放在 Python 脚本中并不是一个好主意,以防您与其他人共享它们,而忘记了您已经这样做了。
本教程建议创建一个单独的 Python 文件config.py
来存储它,但这实际上不是通常的完成方式。
隐藏信息的常用方法是将其放在.env
与主脚本位于同一目录中的文件中,然后从代码中取出信息。
使用该.env
文件是因为它是存储环境变量的传统方式。
如果您想这样做(这可能是最好的选择),那么您必须这样做:
.env
,并使用以下信息填写它:EMAIL_ADDRESS=***
EMAIL_ADDRESS2=***
EMAIL_PASSWORD=***
(请注意,您不需要语音标记。)dotenv
使用以下命令安装模块:pip install python-dotenv
import smtplib
import os
from dotenv import load_dotenv
load_dotenv()
EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS")
EMAIL_ADDRESS2 = os.getenv("EMAIL_ADDRESS2")
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")
def send_email(subject, msg):
try:
server = smtplib.SMTP("smtp-mail.outlook.com:587")
server.ehlo()
server.starttls()
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
message = f"Subject: {subject}\n\n{msg}"
server.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS2, message)
server.quit()
print("email sent ツ")
except:
print("Email failed to send :(")
要了解更多信息dotenv
,请参阅他们的官方 PyPI 页面。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句