Reputation: 1387
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 protected]', [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 protected]', [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
Upvotes: 0
Views: 3245
Reputation: 101
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)
Upvotes: 0
Reputation: 96
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)
Upvotes: 1
Reputation: 7386
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)
Upvotes: 2