提问人:lPitecus 提问时间:11/15/2023 更新时间:11/15/2023 访问量:34
如何在发布请求后发送电子邮件?
How to send an email from after post request?
问:
我正在尝试在使用 flask 从模板博客站点发出帖子请求后发送电子邮件。我需要的所有变量都正确显示,但该函数似乎在代码块中不起作用。send_mail
def send_mail(who_will_receive: str, subject: str, message: str):
"""Sends an email to someone.
:param who_will_receive: str - user who will receive the mail.
:param subject: str - Title of the email.
:param message: str - Message on the body of the mail
"""
my_google_email = "[email protected]"
# noinspection SpellCheckingInspection
password_google = "apppassword"
with smtplib.SMTP(host="smtp.gmail.com", port=587, timeout=120) as connection:
connection.starttls()
connection.login(user=my_google_email, password=password_google)
connection.sendmail(
from_addr=my_google_email,
to_addrs=who_will_receive,
msg=f"Subject: {subject}\n\n{message}".encode("utf8")
) # envia um email para uma conta específicada
@app.route("/contact", methods=["POST", "GET"])
def contact_page():
if request.method == "POST":
name = request.form['name']
email = request.form['email']
phone = request.form['phone']
message = request.form['message']
print(name)
print(email)
print(phone)
print(message) # all these variables are working, but when it comes to send the email, it simply does not appear on my inbox.
send_mail("[email protected]", f"Contact from {name}", f"Name: {name}\nEmail: {email}\nPhone Number: {phone}\nMessage: {message}") # The program executes fine but the email does not appear.
return render_template("contact.html", form_submitted=True)
if request.method == "GET":
return render_template("contact.html")
我尝试更改谷歌应用程序密码,认为这可能是问题所在,但它仍然不断发生。
我还尝试在连接中添加关键字参数,但这似乎与我的问题无关。timeout=120
答:
0赞
ct-7567
11/15/2023
#1
首先要确保您允许在您的 Google 帐户上使用安全性较低的应用程序。 其次,您可以尝试使用一个名为 flask-mail 的库,该库运行良好
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'mailpassword'
app.config['MAIL_DEFAULT_SENDER'] = '[email protected]'
app.config['MAIL_MAX_EMAILS'] = 50
mail = Mail(app)
@app.route("/contact", methods=["POST", "GET"])
def contact_page():
if request.method == "POST":
name = request.form['name']
email = request.form['email']
phone = request.form['phone']
message = request.form['message']
recipient_list = []
with mail.connect() as conn:
for recipient in recipient_list:
msg = Message(subject='subject', recipients=[recipient])
msg.body = f'''
{name}
{email}
{phone}
{message}
'''
conn.send(msg)
return render_template("contact.html", form_submitted=True)
if request.method == "GET":
return render_template("contact.html")
同样,如果你愿意,你可以把它移到功能上,但我以这种方式活着,它更容易理解。
评论