pythonflaskflask-mail

TypeError: can only concatenate list (not "str") to list -


I am trying to get an email when user submit the contact us form. all the data is successfully getting updated in database but getting the err while sending this detail to my mail: -TypeError: can only concatenate list (not "str") to list. there is no '+' sign i have added, where I add anything.

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail, Message
import json

with open('./templates/config.json','r') as f:
    params = json.load(f)["params"]

app = Flask(__name__)
app.config.update(
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=465,
    # MAIL_PORT=587,
    MAIL_USE_SSL=True,
    MAIL_USERNAME=params['gm_user'],
    MAIL_PASSWORD=params['gm_password']

)
mail = Mail(app)


if params['local_server']:
    app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']
else:
    app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Contacts(db.Model):
    sno = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), primary_key=False)
    phone = db.Column(db.String(13), unique=False, nullable=False,primary_key=False)
    email = db.Column(db.String(120), unique=False, nullable=False,primary_key=False)
    msg = db.Column(db.String(500), nullable=False,primary_key=False)



@app.route("/")
def home():
    return render_template('index.html',urlDict = params)

@app.route("/post")
def post():
    return render_template('post.html',urlDict = params)

@app.route("/contact",methods = ['GET','POST'])
def contact():
    if request.method == 'GET':
        return render_template('contact.html',urlDict = params)
    elif request.method =='POST':
        fName = request.form.get("name")
        fEmail = request.form.get("email")
        fMsg = request.form.get("msg")
        fPhone = request.form.get("phone")
        entry = Contacts(name=fName, email=fEmail, msg=fMsg, phone=fPhone)
        db.session.add(entry)
        db.session.commit()
        **mail.send_message(subject='', sender=fEmail, recipients=params['gm_user'], body = '')**

        return render_template('contact.html',urlDict = params)

@app.route("/about")
def about():
    return render_template('about.html',urlDict = params`enter code here`)

app.run(debug=True)

Solution

  • You have to pass a list to recipients in your call to send_message. Right now you are passing a string (i.e. params['gm_user']) which flask_mail is trying to concatenate to a list somewhere internally.

    See one of the first examples in the docs: https://pythonhosted.org/Flask-Mail/#sending-messages.