2

I there a smooth way on how to send html form data with flask mail?

I am trying to get the input from the user from my contact.html.

{% block content %}
<h1 class="title">
  Contact Us
</h1>
<form action="/contact" method="POST">
    <div class="field">
        <div class="control">
            <input class="input is-large" type="name" name="name" placeholder="Name" autofocus="">
        </div>
    </div>

    <div class="field">
        <div class="control">
            <input class="input is-large" type="email" name="email" placeholder="Email" autofocus="">
        </div>
    </div>

    <div class="field">
        <div class="control">
            <input class="textarea is-large" type="text" name="message" placeholder="How can we help you?">
        </div>
    </div>

    <button type="submit" class="button is-block is-info is-large is-fullwidth">Contact us</button>
</form>
</div>
</div>
{% endblock %}

Here is the main.py @route for this page and the code that CAN send an email but i am not able to format it so it also sends the input from the user.


from flask import Blueprint, render_template, request, flash
from flask_login import FlaskLoginClient, login_required, current_user
from . import db
from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)
main = Blueprint('main', __name__)

app.config.update(dict(
    MAIL_SERVER = 'smtp-mail.outlook.com',
    MAIL_PORT = 587,
    MAIL_USE_TLS = True,
    MAIL_USE_SSL = False,
    MAIL_USERNAME = '[email protected]',
    MAIL_PASSWORD = 'mypass'
))

mail = Mail(app)

@main.route('/contact')
def contact():
    return render_template('contact.html')

@main.route('/contact', methods=["POST"])
def contact_post():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        message = request.form.get('message')
        msg = Message('Test', sender='[email protected]', recipients=['[email protected]'])
        msg.body = 'Test mail from:'
        mail.send(msg)
        return 'done'

After adding the code that is referenced below 'msg.body = "Contact form submitted with data:\n\nName: {}\n\nE-mail: {}\n\nMessage: {}".format(name, email, message)' i now get the following error message.

Traceback (most recent call last):
  File "/home/MyPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask/app.py", line 2077, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/MyPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask/app.py", line 1525, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/MyPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask/app.py", line 1523, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/MyPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask/app.py", line 1509, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/home/MyPC/repos/Flask-app/flaskappy/project/main.py", line 38, in contact_post
    mail.send(msg)
  File "/home/MyPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask_mail.py", line 416, in send
    message.send(connection)
  File "/home/MyPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask_mail.py", line 351, in send
    connection.send(self)
  File "/home/MyPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask_mail.py", line 166, in send
    self.host.sendmail(message.sender,
  File "/usr/lib/python3.10/smtplib.py", line 875, in sendmail
    msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 396: ordinal not in range(128)
127.0.0.1 - - [10/Jul/2022 09:45:13] "POST /contact HTTP/1.1" 500 -

After the update to Flask-Mail version 0.9.1 i get these errors.

[2022-07-10 15:08:23,600] ERROR in app: Exception on /contact [POST]
Traceback (most recent call last):
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask/app.py", line 2077, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask/app.py", line 1525, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask/app.py", line 1523, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask/app.py", line 1509, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/home/myPC/repos/Flask-app/flaskappy/project/main.py", line 38, in contact_post
    mail.send(msg)
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask_mail.py", line 492, in send
    message.send(connection)
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask_mail.py", line 427, in send
    connection.send(self)
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask_mail.py", line 190, in send
    message.as_bytes() if PY3 else message.as_string(),
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask_mail.py", line 385, in as_bytes
    return self._message().as_bytes()
  File "/home/myPC/repos/Flask-app/flaskappy/auth/lib/python3.10/site-packages/flask_mail.py", line 307, in _message
    ascii_attachments = current_app.extensions['mail'].ascii_attachments
KeyError: 'mail'
127.0.0.1 - - [10/Jul/2022 15:08:23] "POST /contact HTTP/1.1" 500 -

1 Answer 1

1

You need to add all the posted information to the mail, assuming you want it to the mail body, you could format the msg.body as:

msg.body = "Contact form submitted with data:\n\nName: {}\n\nE-mail: {}\n\nMessage: {}".format(name, email, message)

you can use msg.html to provide html formatted body if you wish to.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the respons, your answer seems clever and i have added that code to my project, but i am now getting Error Code 500 with the following message: "UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 396: ordinal not in range(128)" It seems quiet fatal.... what does this mean?
Is that coming from some code not shown in your question? Would help if you could show which line causes it.
Which version of Flask-mail are you using? i am searching in the flask-mail code for the line self.host.sendmail(message.sender, from your log and i dont see it, i suspect you have an older one. i am using Flask-Mail==0.9.1 and i cannot reproduce your errorm when i feed non-ASCII characters in the mail message, the mail gets sent fine.
The problem is solved your 1st answer helped, the problem is specific and hard to explain i feel that i don't need to explain everything in detail since it was caused by human(me) error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.