新增'flask email-test'命令,可以测试Config.py中邮件配置是否正确,eg: flask email-test -r zhangsan@test.com

This commit is contained in:
azhengzz 2021-04-27 20:12:47 +08:00
parent 262af7dd44
commit 8cdd730536
2 changed files with 30 additions and 5 deletions

View File

@ -194,7 +194,7 @@ def register_before_first_request_funcs(app: Flask):
def register_cli(app: Flask):
"""注册命令"""
@app.cli.command()
@app.cli.command(short_help='初始化当前项目.')
def init():
from flask_migrate import init, migrate, upgrade
click.echo('[flask init] 开始初始化数据库.')
@ -209,3 +209,25 @@ def register_cli(app: Flask):
User.add(username='admin', password='admin', email='admin@example.com')
click.echo('[flask init] 已完成数据库初始化.')
@app.cli.command(short_help='测试邮件服务.')
@click.option('--receiver', '-r', help='收件人邮箱.')
def email_test(receiver: str):
from app.email import send_email
import traceback
if receiver is None or receiver.strip() == '':
click.echo('[flask email-test] 请输入收件人邮箱 eg: flask email-test -r zhangsan@test.com')
return
click.echo('[flask email-test] 开始测试email服务.')
click.echo('[flask email-test] 收件人邮箱: %s.' % receiver)
try:
send_email(
subject="[ApiAutomationTest] 通知",
sender=app.config['ADMINS'][0],
recipients=[receiver],
text_body='您已收到来自ApiAutomationTest的邮件.',
async_send=False,
)
except Exception:
click.echo('[flask email-test] 邮件发送失败,失败原因: \n%s' % traceback.format_exc())
else:
click.echo('[flask email-test] 测试邮件已发送,请查看收件邮箱.')

View File

@ -11,8 +11,11 @@ def send_async_email(app, msg):
mail.send(msg)
def send_email(subject, sender, recipients, text_body=None, html_body=None):
def send_email(subject, sender, recipients, text_body=None, html_body=None, async_send=True):
msg = Message(subject=subject, sender=sender, recipients=recipients, body=text_body, html=html_body)
app = current_app._get_current_object() # 获取被代理的真实对象
t = Thread(target=send_async_email, args=(app, msg))
t.start()
if async_send:
app = current_app._get_current_object() # 获取被代理的真实对象
t = Thread(target=send_async_email, args=(app, msg))
t.start()
else:
mail.send(msg)