Search code examples
pythonhtmlflask-mail

How to pass a variable with href url?


Below is my code to send email using flask in python.

def sendPasswordResetLink(email, token):
    message = Message()
    message.subject = "Reset your password"
    message.sender = "********@gmail.com"
    message.recipients = email.split()
    message.html = '<p>Hello there,</p>\n' \
                   '<p>Please click on the below link to reset your password</p>\n' \
                   '<a href=http://localhost:5002/resetpassword.html?token= +token+>'
    mail.send(message)

Something is wrong in <a href.... line. It is not printing anything in the mail which I am getting. Im using flask-mail extenstion. Can someone give me a quick fix for this. As i said im using flask-mail extension which provides provides a simple interface to set up SMTP with our Flask application and to send messages from our views and scripts.

expected behavior - It should send a mail to my gmail with subject "Reset your password" and in mail body I should get Hello there, Please click on the below link to reset your password. http://localhost:5002/resetpassword.html?token=2

token is a parameter which im sending along with function definition. It contains the userid of the one who requests for the reset password. But the URL is not getting printed in mail which Im getting.


Solution

  • def sendPasswordResetLink(email, token):
        message = Message()
        message.subject = "Reset your password"
        message.sender = "********@gmail.com"
        message.recipients = email.split()
        message.html = '<p>Hello there,</p>\n' \
                       '<p>Please click on the below link to reset your password</p>\n' \
                       '<a href="http://localhost:5002/resetpassword.html?token=' + token + '">Some message here</a>'
        mail.send(message)
    

    Your problem is that you don't escape the '...' string and thus never add token into the mix. But you're also not ending the <a> tag with a </a>. And there for there's no message. Here's some examples.