简体   繁体   中英

Sending a FileField attachment by email

I'm having problems sending a FileField attachment via email. This should send, but doesn't. Is there something I have to configure in my gmail account for this to work?

settings.py

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

views.py

#i.output is the FieldFile
message = 'Thanks for using our website!'
email = EmailMessage('Analysis', message, settings.EMAIL_HOST_USER, [toEmail])
email.attach(filename, i.output.read())
email.send()

I've even received an email from Gmail telling me a sign-in attempt was prevented. Any help? Thanks!

If you don't specify the mime type in your .attach call Django attempts to guess the mime type for you - it may be struggling to correctly guess the mime type given your attachment. If the mime type is incorrect gmail will likely bounce it on receipt. Either set the mime type specifically:

email.attach('image_name.png', img_data, 'image/png')

or you can use the email.attach_file method if you want Django to try to work it out for you:

email = EmailMessage(subject='Analysis', body=message, 
      from_email=settings.EMAIL_HOST_USER, to=[toEmail])
email.attach_file(filename)
email.send(fail_silently=not(settings.DEBUG))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM