如何调整烧瓶邮件以支持两个SMTP帐户 [英] How to adapt flask-mail to support two SMTP accounts

查看:69
本文介绍了如何调整烧瓶邮件以支持两个SMTP帐户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用烧瓶邮件从一个帐户发送邮件,并且工作正常.我在Google中找到的有关多个smtp帐户的唯一信息就是这个旧的

I am using flask-mail to send from one account and it works fine. The unique information about multiple smtp accounts that I found in Google is this old comment.

我所拥有的:

MAIL_USERNAME = config.get('mail_service', 'USER')
MAIL_PASSWORD = config.get('mail_service', 'PASSWD')
MAIL_SERVER = config.get('mail_service', 'MAIL_SERVER')
MAIL_PORT = 587
MAIL_USE_TLS = True

mail = Mail()

def create_app(config_name):
    app = Flask(__name__)
    mail.init_app(app)
    ...


from flask_mail import Message
@app.route("/")
def index():
    msg = Message("Hello", sender="from@example.com", recipients=["to@example.com"])

我不确定什么是最好的方法.可能在发送每封邮件时指定两个已配置的SMTP帐户之一?

I am not sure what is the best approach. Probably when sending each mail specify one of both configured SMTP accounts?

有什么想法要实现吗?

推荐答案

您可以使用 config.json 文件存储两个帐户的配置.然后,自定义函数可以在需要时使用该文件提取值.以下代码显示了两个帐户的简单设置.关键要求是在每个路由中使用邮件对象( mail.init_app())初始化应用之前,更新应用配置.每个smtp帐户在其自己的路由中都有其邮件发送"操作.

You can use a config.json file to store the config for both accounts. Then, a custom function can use that file to extract values whenever required. The following code shows a simple setup of two accounts. The key requirement is to update the app config before initializing the app with the mail object(mail.init_app()) in each route. Each smtp account has its "message send" operation in its own route.

config.json :

配置两个SMTP Gmail帐户

Config for two SMTP Gmail accounts

{
    "MAIL_SERVER" : "smtp.gmail.com",
    "MAIL_PORT" : 587,    
    "MAIL_USE_TLS": "True", 
    "MAIL_USERNAME" : ["smtp1@gmail.com", "smtp2@gmail.com"],
    "MAIL_PASSWORD" : ["pwd_for_smtp1", "pwd_for_smtp2"]
}

代码:

为了测试此代码,我从smtp1@gmail.com向smtp2@gmail.com发送了测试电子邮件,反之亦然.当您在本地主机上访问路由时,应该获得针对每个路由显示的相应消息.

To test this code, I sent test emails from smtp1@gmail.com to smtp2@gmail.com and vice versa. You should get the respective message displayed for each route when you access the route on your localhost.

注意:出于安全原因,您应该使用单独的应用密码进行身份验证,该密码应针对每个SMTP Gmail帐户生成.还应在上面的config.json中为每个帐户的MAIL_PASSWORD键更新应用程序密码.此处.

Note: For security reasons, you should use separate app passwords for authentication which should be generated for each SMTP Gmail account. The app passwords should also be updated in config.json above for the MAIL_PASSWORD key for each account. More details here.

from flask import Flask
from flask_mail import Mail
from flask_mail import Message
import json

def smtp_config(config_name, smtp=1):
    with open(config_name) as f:
            config_data = json.load(f)
    if smtp not in {1,2}:
        raise ValueError("smtp can only be 1 or 2")
    if smtp==2:
        MAIL_USERNAME = config_data['MAIL_USERNAME'][1]
        MAIL_PASSWORD = config_data['MAIL_PASSWORD'][1]
    else:
        MAIL_USERNAME = config_data['MAIL_USERNAME'][0]         
        MAIL_PASSWORD = config_data['MAIL_PASSWORD'][0]        
    MAIL_SERVER = config_data['MAIL_SERVER']
    MAIL_PORT = config_data['MAIL_PORT']    
    MAIL_USE_TLS = bool(config_data['MAIL_USE_TLS'])
    return [MAIL_USERNAME, MAIL_PASSWORD, MAIL_SERVER, MAIL_PORT, MAIL_USE_TLS]

app = Flask(__name__)
mail = Mail()

@app.route("/")
def index():    
    smtp_data = smtp_config('config.json', smtp=1)
    app.config.update(dict(
    MAIL_SERVER = smtp_data[2],
    MAIL_PORT = smtp_data[3],
    MAIL_USE_TLS = smtp_data[4],    
    MAIL_USERNAME = smtp_data[0],
    MAIL_PASSWORD = smtp_data[1],
    ))
    mail.init_app(app)   
    msg = Message("Hello", sender="smtp1@gmail.com", recipients=["smtp2@gmail.com"])    
    msg.body = "This message was sent from smtp1"
    mail.send(msg)
    return "The message was sent from smtp1"

@app.route("/smtp2/")
def smtp2():        
    smtp_data = smtp_config('config.json', smtp=2)
    app.config.update(dict(
    MAIL_SERVER = smtp_data[2],
    MAIL_PORT = smtp_data[3],
    MAIL_USE_TLS = smtp_data[4],    
    MAIL_USERNAME = smtp_data[0],
    MAIL_PASSWORD = smtp_data[1],
    ))
    mail.init_app(app)  
    msg = Message("Hello", sender="smtp2@gmail.com", recipients=["smtp1@gmail.com"])    
    msg.body = "This message was sent from smtp2"
    mail.send(msg)
    return "The message was sent from smtp2"

if __name__=='__main__':    
    app.run(debug=True, port=5000, host='localhost')  

smtp_config()函数接受两个参数: config_name 是config.json文件的路径,而 smtp 具有默认值smtp1帐户配置的值1.该参数可以是1或2.该函数返回特定 smtp 的邮件配置所需的值列表.

The smtp_config() function accepts two args: config_name which is the path of the config.json file and smtp which has a default value of 1 for smtp1 account config. This parameter can either be 1 or 2. The function returns a list of values required for mail configuration for the particular smtp.

然后,在每条路径中,只需使用从上述函数接收的值更新应用程序配置,然后从应用程序设置( mail.init_app())中初始化邮件设置即可.

Then, in each route, just update the app config with the values received from the above function and then initialize the mail settings from the application settings(mail.init_app()).

要添加更多帐户,您可以将smtp帐户名称列表传递给 smtp 以进行唯一标识(而不是上面的数字1和2).当然,您还必须相应地修改 config.json :

To add more accounts, you can pass a list of smtp account names to smtp for unique identification(instead of numbers 1 & 2 above). Of course, you'd also have to modify config.json accordingly:

def smtp_config(config_name, smtp=['smtp1@gmail.com', 'smtp2@gmail.com', 'smtp3@gmail.com'....]):
    #<---code--->
    if x[0]:
        MAIL_USERNAME = 'smtp1@gmail.com'
        ....
    elif x[1]:
        MAIL_USERNAME = 'smtp2@gmail.com'
        ....

这篇关于如何调整烧瓶邮件以支持两个SMTP帐户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆