# Send Email With Attachment

## Email Setup Backend&#x20;

### Settings.py

```python
#gmail_send/settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'olee.techs@gmail.com'
EMAIL_HOST_PASSWORD = 'jzsbfkxvmxiabwow' #past the key or password app here
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'from oleetech'
```

### forms.py

```python
from django import forms
class ContactForm(forms.Form):
    email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)
    attachment = forms.FileField(required=False)

```

### Views.py

```python
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.core.mail import EmailMessage
from django.conf import settings
from .forms import ContactForm

def send_email(request):
    if request.method == 'POST':
        form = ContactForm(request.POST, request.FILES)
        if form.is_valid():
            # Get form data
            email = form.cleaned_data['email']
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            attachment = form.cleaned_data.get('attachment')

            # Create EmailMessage object
            email_message = EmailMessage(
                subject=subject,
                body=message,
                from_email=settings.EMAIL_HOST_USER,
                to=[email],
                
            )

            # Attach file to email
            if attachment:
                email_message.attach(attachment.name, attachment.read(), attachment.content_type)

            # Send email
            try:
                email_message.send()
                return HttpResponse('Email sent successfully.')
            except Exception as e:
                return HttpResponse('Email could not be sent. Error message: {}'.format(str(e)))
    else:
        form = ContactForm()
    return render(request, 'nid/email_form.html', {'form': form})
```

### Templates

**templates/nid/email\_form.html**

```html
<form  method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="submit">
</form>
```

**urls.py**

```python
from django.urls import path
from . import views
urlpatterns = [ 
  path('emailform/', views.send_email, name='emailform'),

]
```

###

### OutPut

<figure><img src="https://664948176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FdX27l90MHtjXhtBupXys%2Fuploads%2FcXG5mrtmPphrypYRI310%2Fsentemailattachmentform.png?alt=media&#x26;token=f4159e3e-7147-491d-9e98-593519a365e7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://664948176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FdX27l90MHtjXhtBupXys%2Fuploads%2FvdxbraNQEunfhHU0nn6Y%2Fsentemailattachmentform%202.png?alt=media&#x26;token=eddcc8cb-fd19-4819-9d4c-8ac2840c5b5b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://664948176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FdX27l90MHtjXhtBupXys%2Fuploads%2Fu4dwLUIsjMKWLi7UNSUb%2Fsentemailattachmentform3.png?alt=media&#x26;token=1b97c82d-3360-4127-9b86-eb8ae036792a" alt=""><figcaption></figcaption></figure>
