0

I am trying to attach a file to an email. The file is uploaded by the user and put into the media folder.

I have tried two ways.

First:

def email_view(request, pk):
    person = Person.objects.get(pk=pk)
    email_to = person.email
    email = EmailMessage(
        'Subject here', 'Here is the message.', 'email@email.com', [email_to])
    email.attach_file(person.upload)
    email.send()

    return redirect('home')

This gives me an error 'FieldFile' object has no attribute 'rfind'

Second:

def email_view(request, pk):
    person = Person.objects.get(pk=pk)
    email_to = person.email

    attachment = str(person.upload)
    attachment = 'http://my_site:8080/media/' + attachment.replace('./', '')
    email = EmailMessage(
        'Subject here', 'Here is the message.', 'email@email.com', [email_to])
    email.attach_file(attachment)
    email.send()

    return redirect('home')

This gives me a page not found. If i copy the url from the error though it takes me to the file. I assume this is happening because of the string format

Mantis
  • 1,357
  • 3
  • 27
  • 49

3 Answers3

2

You get this error because you pass FileField object to attach_file method, not file path. Try to change it to:

email.attach_file(person.upload.file.name)
Dima Kudosh
  • 7,126
  • 4
  • 36
  • 46
  • didn't work. I get `[Errno 2] No such file or directory: u'http://my_site:8080/media/uploads/test.pdf'`. It is definitely there though as if i copy and past the url it takes me to the file – Mantis Oct 23 '15 at 13:29
  • @DimaKudosh Hi, how did you resoled the file does not exist error. Same is happening with me. i can open the file in browser but gives a error no file or directory – ankush madaan Jun 20 '16 at 12:19
1

I had the same error of file not found. This is the tweak I used:

from django.conf import settings
import os

filename = os.path.join(settings.MEDIA_ROOT, person.upload.file.name)
email.attach_file(filename)
colidyre
  • 4,170
  • 12
  • 37
  • 53
mwikya
  • 86
  • 1
  • 3
0

Here's a much cleaner solution. path already contains the absolute path to the file so no need to do os.joins or other concatenations

    email.attach_file(person.upload.file.path)
JR Enriquez
  • 101
  • 1
  • 1
  • 8