Flask-Mail是一个用于发送邮件的Flask扩展。下面是一个使用Flask-Mail库发送简单邮件的示例:
首先,确保你已经安装了Flask-Mail库。如果还没有安装,可以通过pip安装:
pip install Flask-Mail
然后在你的Flask应用中配置并使用Flask-Mail来发送邮件:
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
# 配置邮件服务器设置
app.config['MAIL_SERVER'] = 'smtp.example.com' # 使用你的邮件服务器地址
app.config['MAIL_PORT'] = 587 # 587或25、465,取决于服务器设置
app.config['MAIL_USE_TLS'] = True # 如果服务器支持TLS,设置为True,端口号587或25
app.config['MAIL_USE_SSL'] = True # 如果服务器支持SSL,设置为True,端口后465
app.config['MAIL_USERNAME'] = 'your-email@example.com' # 你的邮箱用户名
app.config['MAIL_PASSWORD'] = 'your-password' # 你的邮箱密码或授权码
app.config['MAIL_DEFAULT_SENDER'] = 'default-sender@example.com' # 默认发件人
mail = Mail(app) # 初始化Mail实例
@app.route('/send_email')
def send_email():
try:
# 创建邮件对象
msg = Message('Hello from Flask-Mail',
sender=app.config['MAIL_DEFAULT_SENDER'],
recipients=['recipient@example.com']) # 收件人列表
# 定义邮件正文
msg.body = "This is a test email sent from Flask using the Flask-Mail extension."
# 添加附件(可选)
# with app.open_resource('path/to/file.txt') as attachment:
# msg.attach("file.txt", "text/plain", attachment.read())
# 发送邮件
mail.send(msg)
return "Email sent successfully!"
except Exception as e:
return f"Error sending email: {str(e)}"
if __name__ == '__main__':
app.run(debug=True)
在这个例子中,我们创建了一个简单的Flask应用,配置了邮件服务器设置,并定义了一个路由/send_email,当访问这个路由时,会触发发送一封测试邮件的功能。请确保替换上述代码中的smtp.example.com、your-email@example.com、your-password以及收件人邮箱地址等信息为实际可用的值。
当前文章价值9.27元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

评论已关闭!