├── .gitignore ├── .vscode └── settings.json ├── README.md ├── django_email ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py ├── emailattachment ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── migrations │ └── __init__.py ├── models.py ├── templates │ └── emailattachment.html ├── tests.py ├── urls.py └── views.py ├── manage.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Django # 2 | *.log 3 | *.pot 4 | *.pyc 5 | __pycache__ 6 | db.sqlite3 7 | media 8 | 9 | # Backup files # 10 | *.bak 11 | 12 | # If you are using PyCharm # 13 | .idea/**/workspace.xml 14 | .idea/**/tasks.xml 15 | .idea/dictionaries 16 | .idea/**/dataSources/ 17 | .idea/**/dataSources.ids 18 | .idea/**/dataSources.xml 19 | .idea/**/dataSources.local.xml 20 | .idea/**/sqlDataSources.xml 21 | .idea/**/dynamic.xml 22 | .idea/**/uiDesigner.xml 23 | .idea/**/gradle.xml 24 | .idea/**/libraries 25 | *.iws /out/ 26 | 27 | # Python # 28 | *.py[cod] 29 | *$py.class 30 | 31 | # Distribution / packaging 32 | .Python build/ 33 | develop-eggs/ 34 | dist/ 35 | downloads/ 36 | eggs/ 37 | .eggs/ 38 | lib/ 39 | lib64/ 40 | parts/ 41 | sdist/ 42 | var/ 43 | wheels/ 44 | *.egg-info/ 45 | .installed.cfg 46 | *.egg 47 | *.manifest 48 | *.spec 49 | 50 | # Installer logs 51 | pip-log.txt 52 | pip-delete-this-directory.txt 53 | 54 | # Unit test / coverage reports 55 | htmlcov/ 56 | .tox/ 57 | .coverage 58 | .coverage.* 59 | .cache 60 | .pytest_cache/ 61 | nosetests.xml 62 | coverage.xml 63 | *.cover 64 | .hypothesis/ 65 | 66 | # Jupyter Notebook 67 | .ipynb_checkpoints 68 | 69 | # pyenv 70 | .python-version 71 | 72 | # celery 73 | celerybeat-schedule.* 74 | 75 | # SageMath parsed files 76 | *.sage.py 77 | 78 | # Environments 79 | .env 80 | .venv 81 | env/ 82 | venv/ 83 | ENV/ 84 | env.bak/ 85 | venv.bak/ 86 | 87 | # mkdocs documentation 88 | /site 89 | 90 | # mypy 91 | .mypy_cache/ 92 | 93 | # Sublime Text # 94 | *.tmlanguage.cache 95 | *.tmPreferences.cache 96 | *.stTheme.cache 97 | *.sublime-workspace 98 | *.sublime-project 99 | 100 | # sftp configuration file 101 | sftp-config.json 102 | 103 | # Package control specific files Package 104 | Control.last-run 105 | Control.ca-list 106 | Control.ca-bundle 107 | Control.system-ca-bundle 108 | GitHub.sublime-settings 109 | 110 | # Visual Studio Code # 111 | .vscode/* 112 | !.vscode/settings.json 113 | !.vscode/tasks.json 114 | !.vscode/launch.json 115 | !.vscode/extensions.json 116 | .history 117 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "env/bin/python3.5" 3 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # How to Send Email With Attachments in Django 2 | 3 | ## Tutorial Link - http://studygyaan.com/django/how-to-send-email-with-attachments-in-django 4 | 5 | In this tutorial, you will learn how to send email with multiple attachments in Django. You will also learn how to send email with a single attachment. Here, I will explain how to setup your SendGrid Account for Sending Emails for your Django Application. I will also explain how to set your Email Host in the settings.py file, in your application 6 | 7 | ### Setup 8 | 1. Create a folder and put all the files inside it. 9 | 2. Create a virtual environtment - `virtualenv env` 10 | 3. Activate VirtualENV - `source env/bin/activate` 11 | 4. Run requirements.txt - `pip3 install -r requirements.txt` 12 | 5. Run the Application - `python3 manage.py runserver` 13 | 6. Go to - http://localhost:8000/ 14 | 15 | ### Make Sure You Change your Email Host Password in Settings.py file. 16 | -------------------------------------------------------------------------------- /django_email/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/studygyaan/how-to-send-email-with-attachments-in-django/4e320f3277d20e5ad84bf0dc23ac3f4aceaa758e/django_email/__init__.py -------------------------------------------------------------------------------- /django_email/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for django_email project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.2. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'd$cnq7o9e8hfz7%el^hpz-#u)!l(dig+kt&+oloh-d*ka-c_9y' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 41 | 'crispy_forms', # Library 42 | 43 | 'emailattachment', # Register App 44 | ] 45 | 46 | MIDDLEWARE = [ 47 | 'django.middleware.security.SecurityMiddleware', 48 | 'django.contrib.sessions.middleware.SessionMiddleware', 49 | 'django.middleware.common.CommonMiddleware', 50 | 'django.middleware.csrf.CsrfViewMiddleware', 51 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 52 | 'django.contrib.messages.middleware.MessageMiddleware', 53 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 54 | ] 55 | 56 | ROOT_URLCONF = 'django_email.urls' 57 | 58 | TEMPLATES = [ 59 | { 60 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 61 | 'DIRS': [], 62 | 'APP_DIRS': True, 63 | 'OPTIONS': { 64 | 'context_processors': [ 65 | 'django.template.context_processors.debug', 66 | 'django.template.context_processors.request', 67 | 'django.contrib.auth.context_processors.auth', 68 | 'django.contrib.messages.context_processors.messages', 69 | ], 70 | }, 71 | }, 72 | ] 73 | 74 | WSGI_APPLICATION = 'django_email.wsgi.application' 75 | 76 | 77 | # Database 78 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 79 | 80 | DATABASES = { 81 | 'default': { 82 | 'ENGINE': 'django.db.backends.sqlite3', 83 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 84 | } 85 | } 86 | 87 | 88 | # Password validation 89 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 90 | 91 | AUTH_PASSWORD_VALIDATORS = [ 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 103 | }, 104 | ] 105 | 106 | 107 | # Internationalization 108 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 109 | 110 | LANGUAGE_CODE = 'en-us' 111 | 112 | TIME_ZONE = 'UTC' 113 | 114 | USE_I18N = True 115 | 116 | USE_L10N = True 117 | 118 | USE_TZ = True 119 | 120 | 121 | # Static files (CSS, JavaScript, Images) 122 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 123 | 124 | STATIC_URL = '/static/' 125 | 126 | CRISPY_TEMPLATE_PACK = 'bootstrap4' 127 | 128 | 129 | # Email 130 | EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' 131 | EMAIL_HOST = 'smtp.sendgrid.net' 132 | EMAIT_PORT = 587 133 | EMAIL_USE_TLS = True 134 | EMAIL_HOST_USER = 'apikey' 135 | EMAIL_HOST_PASSWORD = 'SG.oDN9bU0asda64GvHLF5w.gXsdfsdfsfsdfsdfsdRD1PcqSkn-EfiftfsdfsNWU' 136 | -------------------------------------------------------------------------------- /django_email/urls.py: -------------------------------------------------------------------------------- 1 | """django_email URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | from emailattachment import urls as emailattachment_urls 19 | 20 | 21 | urlpatterns = [ 22 | path('admin/', admin.site.urls), 23 | path('', include(emailattachment_urls)), 24 | ] 25 | -------------------------------------------------------------------------------- /django_email/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_email project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_email.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /emailattachment/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/studygyaan/how-to-send-email-with-attachments-in-django/4e320f3277d20e5ad84bf0dc23ac3f4aceaa758e/emailattachment/__init__.py -------------------------------------------------------------------------------- /emailattachment/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /emailattachment/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class EmailattachmentConfig(AppConfig): 5 | name = 'emailattachment' 6 | -------------------------------------------------------------------------------- /emailattachment/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | class EmailForm(forms.Form): 4 | email = forms.EmailField() 5 | subject = forms.CharField(max_length=100) 6 | attach = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) 7 | message = forms.CharField(widget = forms.Textarea) -------------------------------------------------------------------------------- /emailattachment/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/studygyaan/how-to-send-email-with-attachments-in-django/4e320f3277d20e5ad84bf0dc23ac3f4aceaa758e/emailattachment/migrations/__init__.py -------------------------------------------------------------------------------- /emailattachment/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /emailattachment/templates/emailattachment.html: -------------------------------------------------------------------------------- 1 | {% load crispy_forms_tags %} 2 | 3 | 4 | 5 | 6 | 7 | Email Attachment - Django and Python 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 |
17 |
18 |

Django Email Attachment

19 | 20 | {% if error_message %} 21 | 24 | {% endif %} 25 | 26 | {% if email_form %} 27 |
28 | {% csrf_token %} 29 | {{email_form|crispy}} 30 | 31 |
32 | {% endif %} 33 | 34 |
35 |
36 |
37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /emailattachment/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /emailattachment/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from emailattachment.views import EmailAttachementView 3 | 4 | urlpatterns = [ 5 | path('', EmailAttachementView.as_view(), name='emailattachment') 6 | 7 | ] -------------------------------------------------------------------------------- /emailattachment/views.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponseRedirect 2 | from django.shortcuts import render 3 | from django.views import View 4 | 5 | from django.core.mail import EmailMessage 6 | 7 | from django.conf import settings 8 | from .forms import EmailForm 9 | 10 | class EmailAttachementView(View): 11 | form_class = EmailForm 12 | template_name = 'emailattachment.html' 13 | 14 | def get(self, request, *args, **kwargs): 15 | form = self.form_class() 16 | return render(request, self.template_name, {'email_form': form}) 17 | 18 | def post(self, request, *args, **kwargs): 19 | form = self.form_class(request.POST, request.FILES) 20 | 21 | if form.is_valid(): 22 | 23 | subject = form.cleaned_data['subject'] 24 | message = form.cleaned_data['message'] 25 | email = form.cleaned_data['email'] 26 | files = request.FILES.getlist('attach') 27 | 28 | try: 29 | mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email]) 30 | for f in files: 31 | mail.attach(f.name, f.read(), f.content_type) 32 | mail.send() 33 | return render(request, self.template_name, {'email_form': form, 'error_message': 'Sent email to %s'%email}) 34 | except: 35 | return render(request, self.template_name, {'email_form': form, 'error_message': 'Either the attachment is too big or corrupt'}) 36 | 37 | return render(request, self.template_name, {'email_form': form, 'error_message': 'Unable to send email. Please try again later'}) 38 | 39 | # Single File Attachment 40 | # def post(self, request, *args, **kwargs): 41 | # form = self.form_class(request.POST, request.FILES) 42 | 43 | # if form.is_valid(): 44 | 45 | # subject = form.cleaned_data['subject'] 46 | # message = form.cleaned_data['message'] 47 | # email = form.cleaned_data['email'] 48 | # attach = request.FILES['attach'] 49 | 50 | # try: 51 | # mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email]) 52 | # mail.attach(attach.name, attach.read(), attach.content_type) 53 | # mail.send() 54 | # return render(request, self.template_name, {'email_form': form, 'error_message': 'Sent email to %s'%email}) 55 | # except: 56 | # return render(request, self.template_name, {'email_form': form, 'error_message': 'Either the attachment is too big or corrupt'}) 57 | 58 | # return render(request, self.template_name, {'email_form': form, 'error_message': 'Unable to send email. Please try again later'}) -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_email.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django==2.2.2 2 | django-crispy-forms==1.7.2 3 | pytz==2019.1 4 | sqlparse==0.3.0 5 | --------------------------------------------------------------------------------