Django HTML表单发送附件电子邮件 [英] Django HTML Form Send Attachment Emails

查看:51
本文介绍了Django HTML表单发送附件电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此导入时,我遇到以下问题

I have the following problem using this import

from django.core.mail.message import EmailMessage

我的代码看起来像这样:

And my code looks something like this:

if request.method == 'POST':
    email = EmailMessage()
    email.subject = "Test"
    email.body = mainMessage
    email.from_email = "SMTP <XXX@XXX.net>"
    email.to = [ "XXX@XXX.net" ]
    email.attach_file(file)

    email.send()

然后我使用以下命令检查文件:

And I check for my file with:

if 'file' in request.FILES:
    file = request.FILES['file']
else:
    file = False

这就是我的HTML外观

And this is what my HTML looks like

<form method="post" action="{% url 'myurl' %}" enctype="multipart/form-data">
                {% csrf_token %}

    <input type="file" name="file" required><br>

    <input type="submit" name="submit" value="Submit">
</form>

如果我选择一个文件,如何使它作为附件随该电子邮件一起发送?如果我删除 email.attach_file(file),它可以正常工作,但只发送文本.

If I choose a file, how can I make it to be sent as an attachment with that email? If I remove email.attach_file(file) it works just fine, but only sends the text.

推荐答案

if request.method == 'POST' and request.FILES['file']:
    file = request.FILES['file'] 
    if (str(file.content_type) == 'image/jpeg' 
       or str(file.content_type) == 'image/png'):
        if (int(file.size) <= 5000000):
            fs = FileSystemStorage()
            filename = fs.save('YOUR_DIRECTORY/' + file.name, file)

            email = EmailMessage()
            email.subject = "XXX | Bildupload"
            email.body = mainMessage
            email.from_email = "SMTP <xxx@xxx.net>"
            email.to = ["xxx@xxx.net"]
            email.attach_file(filename)
            email.send()

            answer = 'Die Datei wurde erfolgreich hochgeladen'
            errorAnswer = ''
            return render(request, 'app/hochladen.html', {
                'answer': answer
            })
        else:
            errorAnswer = 'Der Upload hat nicht funktioniert.' 
    else:
        errorAnswer = 'Der Upload hat nicht funktioniert.'
    return render(request, 'app/hochladen.html', {
        'errorAnswer': errorAnswer
    })

如果有人想知道如何做,可以使用上面发布的代码.您可以删除第二和第三个if语句,因为它们会检查大小和文件类型.

If anyone is wondering on how to do it, it's possible with the code posted above. You can delete the second and third if statement, as they check for the size and filetype.

我找到的唯一答案是首先将文件上传到服务器,然后从那里访问它.尽管我不知道在发送电子邮件并附加附件后如何将其删除.

The only answer I've found was to first upload the file to the server, and then access it from there. Although I don't know how to delete it after sending the email and attaching it.

您需要正确配置settings.py并添加/media/文件夹.

And you need to configure your settings.py correctly and add a /media/ Folder.

这篇关于Django HTML表单发送附件电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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