尝试发送电子邮件附件时出错

2024-03-28 18:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在程序中使用以下功能发送电子邮件:

def send_email(subject, sender, recipients, text_body):
    FILE_TYPES = set(['txt', 'doc', 'docx', 'odt', 'pdf', 'rtf', 'text', 'wks', 'wps', 'wpd'])
    form = ApplicationForm (request.files)
    submit_name = form.file_upload.data.filename
    mail = Mail(app)
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    if '.' in submit_name and submit_name.rsplit('.', 1)[1] in FILE_TYPES:
        filename = secure_filename(submit_name)
        form.file_upload.data.save('uploads/' + filename)
        with app.open_resource(filename) as fp:
            msg.attach(filename, fp.read())
            mail.send(msg)

电子邮件工作正常,并发送到正确的用户,但附件没有,我相信我可能是引用这个错误的文件附件来自表单。你知道吗

我已经使用了下面的功能来保存附件,这很好,所以我不知道为什么上面的不工作,有人可以帮助吗?你知道吗

if '.' in submit_name and submit_name.rsplit('.', 1)[1] in FILE_TYPES:
    filename = secure_filename(submit_name)
    form.file_upload.data.save('uploads/' + filename)
    return redirect('home')

编辑:尝试提交时收到的错误消息为:

[Errno 2] No such file or directory: 'C:\\Users\\richard.danvers\\application\\answer.docx'

看起来“上传”没有包含在路径中,有人知道如何包含这个吗?你知道吗


Tags: textnameinformdatabodymsgfilename
2条回答

在附加文件之前发送电子邮件:

mail.send(msg)
if '.' in submit_name and submit_name.rsplit('.', 1)[1] in FILE_TYPES:
    ...

需要在中指定内容类型附加消息争论。你知道吗

例如“文本/纯文本”

相关问题 更多 >