如何在超链接中传递用户 ID 等参数?



我有一个HTML页面,里面有一个超链接。这封 html 电子邮件将通过 Outlook 发送给用户(我已经使用 flask python 编写了邮件功能(,当用户单击电子邮件正文上的超链接时,它最终会打开另一个页面。此页面将是相同的,但是,根据用户的电子邮件ID,不同用户的页面内容会有所不同。

现在,我的要求是通过超链接传递用户电子邮件 ID,以便我可以根据电子邮件 ID 显示不同的内容。可以通过超链接完成吗?如您所知,Outlook 使用 Word Microsoft 作为呈现引擎,那么通过超链接传递参数会很困难吗?

或者,我可以在发送邮件时通过烧瓶功能传递电子邮件 ID 吗?

我的烧瓶功能将邮件发送到 Outlook 如下

from flask import Flask, render_template
from flask_mail import Mail, Message

app = Flask(__name__)
app.config.update(
DEBUG=True,
MAIL_SERVER='My Company SMTP MAIL SERVER',
MAIL_PORT=My Company SMTP PORT NUMBER,
# MAIL_USE_SSL=True,
MAIL_USERNAME='XXXXX.YYYY@mycompanyname.com',
)
mail = Mail(app)

@app.route('/')
def mailSend():
try:
recipeint_emails = fetch_recipient_emails
msg = Message("Send Mail Tutorial!",
sender="XXXXX.YYYY@mycompanyname.com",
recipients=recipeint_emails)
msg.html = render_template('linkPage.html')
mail.send(msg)
return 'Mail sent!'
except Exception as e:
print(type(e))
print(e)
return 'error'

链接页面.html将包含下面提到的超链接

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hyperlinkdemo</title>
</head>
<body>
<a href="https://hyperlinkflask.azurewebsites.net/helloworld" target="_blank">Visit Dynamic Page</a>
</body>
</html>

任何建议都会非常有帮助。

Flask已经有一个内置函数url_for,可以正确生成带有额外参数的链接。请参阅此文档

更新

  • 建议为路由选择准确的名称
  • 建议在命名视图时使用snake_case
  • 我建议您参考官方Flask-Mail文档部分Bulk Mail
@app.route('/bulk-email')
def bulk_mail():
[..]
# Get all users first
with mail.connect() as conn:
for user in users:
msg = Message(subject="Tutorial",
sender="XXXXX.YYYY@mycompanyname.com",
recipients=[user.email])
# pass dynamically the user to the template
msg.html = render_template('linkPpage.html', user=user)
conn.send(msg)

linkPage.html模板中你可以做

<p>Dear {{ user.username }},</p>
<p>
<a href = "{{ url_for('link_tutorial', user_id=user.id, _external=True) }}">Open Link tutorial</a>
</p> //added double quotation

您必须实现link_tutorial函数的逻辑,当用户单击链接时,它将被重定向到您的应用程序,向他显示自定义页面/教程:

@app.route('/link-tutorial/<int:user_id>')
def link_tutorial(user_id):
# fetch the user with the given user_id and render the right template for him.
[..]
return render_template('tutorial.html')

最后,我建议您使用异步任务队列celeryFlask-Mail更有效地处理批量电子邮件,因为发送邮件是一项阻止任务,并且您的应用程序将非常慢且无响应。

最新更新