python库flask_mail使用示例

2024-05-22 10:42 python库flask_mail使用示例已关闭评论

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.comyour-email@example.comyour-password以及收件人邮箱地址等信息为实际可用的值。

当前文章价值9.27元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

你可能感兴趣的文章

来源:每日教程每日一例,深入学习实用技术教程,关注公众号TeachCourse
转载请注明出处: https://teachcourse.cn/3440.html ,谢谢支持!

资源分享

分类:python 标签:, ,
Python常用100个关键字详细示例(2) Python常用100个关键字详细示例
Python常用100个关键字详细示例(4) Python常用100个关键字详细示例
Android SDK “Error when loading the SDK” Android SDK “Error when
kotlin基础语法 kotlin基础语法

评论已关闭!