通过电子邮件发送FileField附件

时间:2015-09-09 19:00:51

标签: python django email email-attachments

我在通过电子邮件发送FileField附件时遇到问题。这应该发送,但不发送。我的gmail帐户中是否有必要配置此功能?

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

我甚至收到了Gmail发来的电子邮件,告诉我登录尝试已被阻止。有帮助吗?谢谢!

1 个答案:

答案 0 :(得分:0)

如果你没有在你的.attach调用中指定mime类型,Django会尝试为你猜测mime类型 - 在给定你的附件时,可能很难正确猜测mime类型。如果mime类型不正确,gmail可能会在收到时将其弹回。要么专门设置mime类型:

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

或者你可以使用email.attach_file方法,如果你想让Django尝试为你解决这个问题:

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