在Flask中實現電子郵件發送可以使用Python的smtplib庫。下面是一個簡單的例子:
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()
在上面的例子中,我們定義了一個send_email函數來發送電子郵件。然后我們在Flask應用中創建了一個路由/send_email,通過POST請求發送郵件的主題、內容和收件人郵箱地址。當接收到請求時,我們調用send_email函數發送電子郵件。