Heroku Django邮件未发送

2024-06-17 13:43:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Django RestFramework和ReactjS发送邮件。在本地机器上,发送邮件可以正常工作,但是如果我在Heroku上部署代码,我总是会遇到如下错误

Object of type NameError is not JSON serializable or SmtpAuthentication Error Object is not Serializable

有人能帮我吗

序列化程序.py


class contactSerializer(serializers.Serializer):
    name = serializers.CharField()
    email = serializers.CharField()
    subject = serializers.CharField()
    message = serializers.CharField()
   

    def validate(self, data):
        print("data**********", data)
        return data
        
    def save(self):
        email = self.validated_data['email']
        message = self.validated_data['message']
        subject = self.validated_data['subject']
        name = self.validated_data['name']
        cntct= contacts(name=name, email=email,subject=subject, message=message)
       
        send_mail(subject, 'Name :'+name+'\n\n'+email+'\n\n\n\n' +
                      message, email,[email])
        return cntct.save()

views.py


class contactCreateandMailSend(generics.GenericAPIView):
    permission_classes = (permissions.AllowAny,)
    serializer_class = contactSerializer
    def post(self, request, format=None):
        serializer = contactSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        try:
            serializer.save()
            return Response({'sucesss': 'Message has been sent'})
        except Exception as err:
            return Response({'errors': err})

设置.py



# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

import dj_database_url

db_from_env= dj_database_url.config(conn_max_age=600, ssl_require=True)
DATABASES['default'].update(db_from_env)
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
CORS_ORIGIN_ALLOW_ALL = True
CSRF_COOKIE_HTTPONLY = True
STATICFILES_DIRS = [

    os.path.join(BASE_DIR, os.path.join(BASE_DIR, 'build/static')),
    os.path.join(BASE_DIR, os.path.join(BASE_DIR, 'build')),
    os.path.join(BASE_DIR, 'media'),

]
WHITENOISE_MIMETYPES = {
    '.xsl': 'application/xml'
}
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),

    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 3
}




EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
# If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

EMAIL_HOST_USER = os.environ.get('DB_USER')
EMAIL_HOST_PASSWORD = os.environ.get('DB_PASS')
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG=os.environ.get("DEBUG_VAL")
django_heroku.settings(locals())

响应体

TypeError at /contacts/mail/
Object of type SMTPAuthenticationError is not JSON serializable

Request Method: POST
Request URL: https://estate-real-appp.herokuapp.com/contacts/mail/
Django Version: 3.1.4
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.7.4
Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages']
Server time: Fri, 11 Dec 2020 03:25:22 +0000
Installed Applications:
['Account',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'drf_yasg',
 'immobilien',
 'listinghouse',
 'contacts',
 'corsheaders']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware']


Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response
    response = response.render()
  File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/app/.heroku/python/lib/python3.7/site-packages/rest_framework/response.py", line 70, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "/app/.heroku/python/lib/python3.7/site-packages/rest_framework/renderers.py", line 103, in render
    allow_nan=not self.strict, separators=separators
  File "/app/.heroku/python/lib/python3.7/site-packages/rest_framework/utils/json.py", line 25, in dumps
    return json.dumps(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/app/.heroku/python/lib/python3.7/site-packages/rest_framework/utils/encoders.py", line 67, in default
    return super().default(obj)
  File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '

Exception Type: TypeError at /contacts/mail/
Exception Value: Object of type SMTPAuthenticationError is not JSON serializable
Request information:
USER: AnonymousUser

GET: No GET data

POST: No POST data

FILES: No FILES data




Tags: djangoinpyselftrueappdataheroku