简体   繁体   English

通过电子邮件发送FileField附件

[英]Sending a FileField attachment by email

I'm having problems sending a FileField attachment via email. 我在通过电子邮件发送FileField附件时遇到问题。 This should send, but doesn't. 这应该发送,但不发送。 Is there something I have to configure in my gmail account for this to work? 我必须在我的gmail帐户中进行配置才能正常工作吗?

settings.py 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 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. 我什至收到Gmail发出的电子邮件,告诉我阻止了登录尝试。 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. 如果您未在.attach调用中指定mime类型,则Django会尝试为您猜测mime类型-在给定附件的情况下,正确猜测mime类型可能会很困难。 If the mime type is incorrect gmail will likely bounce it on receipt. 如果mime类型不正确,gmail可能会在收据上将其退回。 Either set the mime type specifically: 要么专门设置mime类型:

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: 或者,如果您希望Django尝试为您解决问题,则可以使用email.attach_file方法:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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