如何在使用 Flask Mail 时设置发件人电子邮件 ID

问题描述 投票:0回答:3

我正在使用 Flak Mail 从网站的联系表单发送电子邮件。联系表单还有一个

sender
电子邮件 ID 字段。因此,当我收到“收件人”电子邮件 ID 的电子邮件时,我希望将
from
设置为
sender
电子邮件 ID,以便在表单上输入值。以下是处理电子邮件的类:

from flask_mail import Mail, Message

class SendMail:

    def __init__(self, app):
        app.config['MAIL_SERVER']='smtp.gmail.com'
        app.config['MAIL_PORT'] = 465
        app.config['MAIL_USERNAME'] = '[email protected]'
        app.config['MAIL_PASSWORD'] = '<password>'
        app.config['MAIL_USE_TLS'] = False
        app.config['MAIL_USE_SSL'] = True
        self.recipient_email = '[email protected]'
        self.app = app
        self.mail = Mail(self.app)

    def compile_mail(self, name, email_id, phone_no, msg):
        message = Message(name+" has a query",
                          sender = email_id,
                          recipients=[self.recipient_email])
        message.html = "<b>Name : </b>"+name+"<br><b>Phone No :</b> "+phone_no+"<br><b>Message : </b>"+msg
        return message

    def send_mail(self, name, email_id, phone_no, msg):
        message = self.compile_mail(name, email_id, phone_no, msg)
        with self.app.app_context():
            self.mail.send(message)

send_mail
方法接收四个参数,它们是在联系表单上输入的字段。问题是,当我像这样发送电子邮件时,收到的电子邮件中的
from
被设置为 SMTP MAIL_USERNAME
[email protected]
,尽管事实上我将 Message 对象中的
sender
参数设置为从 SMTP 接收的
email_id
联系表。 无法弄清楚如何将发送者设置为我想要的值。

python flask smtp flask-mail
3个回答
2
投票

您是否检查过您传入的

email_id
是否就是您所认为的那样?

Flask Mail 源代码表明,如果您传入的

sender
为假(例如 None 或空字符串),它只会使用默认值。


1
投票

如果您的意思是要将发件人名称设置为非电子邮件地址(例如发件人=“Stackoverflow”),您可以将发件人争论设置为元组。

message = Message(name+" has a query",
                  sender = (email_id, app.config["MAIL_USERNAME"]),
                  # 'email_id' will replace 'app.config["MAIL_USERNAME"]' as the name that shows up in your email
                  recipients=[self.recipient_email])

0
投票

将此添加到您的邮件配置中:

MAIL_DEFAULT_SENDER:默认 无(替换为您希望作为发件人的电子邮件)。例如

MAIL_DEFAULT_SENDER:“[电子邮件受保护]

© www.soinside.com 2019 - 2024. All rights reserved.