在Flask中實(shí)現(xiàn)電子郵件發(fā)送可以使用Python的smtplib庫。下面是一個(gè)簡單的例子:
from flask import Flask, request
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
app = Flask(__name__)
def send_email(subject, message, to_email):
from_email = 'your_email@example.com'
password = 'your_password'
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(from_email, password)
text = msg.as_string()
server.sendmail(from_email, to_email, text)
server.quit()
@app.route('/send_email', methods=['POST'])
def send_email_route():
data = request.get_json()
subject = data['subject']
message = data['message']
to_email = data['to_email']
send_email(subject, message, to_email)
return 'Email sent successfully!'
if __name__ == '__main__':
app.run()
在上面的例子中,我們定義了一個(gè)send_email函數(shù)來發(fā)送電子郵件。然后我們在Flask應(yīng)用中創(chuàng)建了一個(gè)路由/send_email,通過POST請求發(fā)送郵件的主題、內(nèi)容和收件人郵箱地址。當(dāng)接收到請求時(shí),我們調(diào)用send_email函數(shù)發(fā)送電子郵件。