Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
trttungdev committed Jul 3, 2023
0 parents commit 0966d56
Show file tree
Hide file tree
Showing 36 changed files with 495 additions and 0 deletions.
Binary file added db.sqlite3
Binary file not shown.
Binary file added email.xlsx
Binary file not shown.
Binary file added email_IK0jNG7.xlsx
Binary file not shown.
Binary file added email_hRpByWL.xlsx
Binary file not shown.
Binary file added email_sender/AIConsultantBlackSmall.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file added email_sender/__init__.py
Empty file.
Binary file added email_sender/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added email_sender/__pycache__/admin.cpython-310.pyc
Binary file not shown.
Binary file added email_sender/__pycache__/apps.cpython-310.pyc
Binary file not shown.
Binary file added email_sender/__pycache__/models.cpython-310.pyc
Binary file not shown.
Binary file added email_sender/__pycache__/script.cpython-310.pyc
Binary file not shown.
Binary file added email_sender/__pycache__/views.cpython-310.pyc
Binary file not shown.
3 changes: 3 additions & 0 deletions email_sender/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions email_sender/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class EmailSenderConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'email_sender'
Empty file.
Binary file not shown.
3 changes: 3 additions & 0 deletions email_sender/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
125 changes: 125 additions & 0 deletions email_sender/script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import smtplib
import pandas as pd
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formataddr


def send_emails(sender_email, sender_password, subject, email_content, recipients_file_path):
df = pd.read_excel(recipients_file_path)
receiver_emails = df.iloc[:, 0].tolist()
total_emails = len(receiver_emails)
successful_emails = []

with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
try:
server.login(sender_email, sender_password)
except smtplib.SMTPAuthenticationError:
return {"status": "error", "message": "Authentication Failed"}

for i, receiver_email in enumerate(receiver_emails, start=1):
if send_email(server, sender_email, receiver_email, subject, email_content):
successful_emails.append(receiver_email)

progress = int((i / total_emails) * 100)
time.sleep(1) # Delay between sending emails

return {"status": "success", "successful_emails": successful_emails}


def send_email(server, sender_email, receiver_email, subject, email_content):
message = MIMEMultipart()
message["From"] = formataddr(("AI Consultant", sender_email))
message["To"] = receiver_email
message["Subject"] = subject

email_content_formatted = email_content.replace("\n", "<br><br>")
html_content = f"""
<html>
<head>
<style>
body {{
font-family: Arial, sans-serif;
font-size: 14px;
line-height: 1.6;
margin: 0;
padding: 0;
}}
.email-container {{
max-width: 1500px;
margin: 0 auto;
padding: 20px;
}}
.email-header {{
text-align: center;
margin-bottom: 20px;
}}
.email-header h2 {{
color: #333333;
font-size: 24px;
font-weight: 700;
line-height: 1.2;
margin: 0;
}}
.email-content {{
background-color: #f9f9f9;
padding: 20px;
text-align: justify;
}}
.email-content p {{
color: #555555;
font-size: 16px;
line-height: 1.6;
margin: 0 0 10px;
}}
.email-content hr {{
border: none;
border-top: 1px solid #dddddd;
margin: 20px 0;
}}
.logo {{
display: block;
margin: 0 auto;
width: 60px;
}}
</style>
</head>
<body>
<div class="email-container">
<div class="email-header">
<h2>{subject}</h2>
</div>
<div class="email-content">
{email_content_formatted}
<hr>
</div>
<img src="cid:logo_image" alt="Logo" class="logo">
</div>
</body>
</html>
"""

# Attach the logo image
logo_path = "./email_sender/AIConsultantBlackSmall.png"
with open(logo_path, "rb") as logo_file:
logo_image = MIMEImage(logo_file.read())
logo_image.add_header("Content-ID", "<logo_image>")
message.attach(logo_image)

message.attach(MIMEText(html_content, "html"))
email_message = message.as_string().encode("utf-8")
try:
server.sendmail(sender_email, receiver_email, email_message)
return True
except smtplib.SMTPException:
return False
3 changes: 3 additions & 0 deletions email_sender/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
23 changes: 23 additions & 0 deletions email_sender/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from django.shortcuts import render
from django.core.files.storage import default_storage
from .script import send_emails

def send_email_view(request):
if request.method == 'POST':
sender_email = request.POST.get('sender_email')
sender_password = request.POST.get('sender_password')
subject = request.POST.get('subject')
email_content = request.POST.get('email_content')
recipients_file = request.FILES['recipients_file']

# Save the uploaded file
file_path = default_storage.save('email.xlsx', recipients_file)

recipients_file_path = default_storage.path(file_path)

# Send the emails
result = send_emails(sender_email, sender_password, subject, email_content, recipients_file_path)

return render(request, 'result.html', {'result': result})

return render(request, 'send_email.html')
Binary file added email_vT607lc.xlsx
Binary file not shown.
Empty file added email_webapp/__init__.py
Empty file.
Binary file added email_webapp/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added email_webapp/__pycache__/settings.cpython-310.pyc
Binary file not shown.
Binary file added email_webapp/__pycache__/urls.cpython-310.pyc
Binary file not shown.
Binary file added email_webapp/__pycache__/wsgi.cpython-310.pyc
Binary file not shown.
16 changes: 16 additions & 0 deletions email_webapp/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for email_webapp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'email_webapp.settings')

application = get_asgi_application()
127 changes: 127 additions & 0 deletions email_webapp/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""
Django settings for email_webapp project.
Generated by 'django-admin startproject' using Django 4.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-ug46llrm1$wt)54st&5$1)0e1w2y_$&wo=4a2zs$@6kcms270p'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'email_sender'
]

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',
]

ROOT_URLCONF = 'email_webapp.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR , 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'email_webapp.wsgi.application'


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

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/4.2/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/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

STATICFILES_DIRS = [
BASE_DIR / "static"
]
23 changes: 23 additions & 0 deletions email_webapp/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
URL configuration for email_webapp project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from email_sender import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.send_email_view , name="send_email"),
]
16 changes: 16 additions & 0 deletions email_webapp/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for email_webapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'email_webapp.settings')

application = get_wsgi_application()
Binary file added email_yDalC3v.xlsx
Binary file not shown.
22 changes: 22 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'email_webapp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Loading

0 comments on commit 0966d56

Please sign in to comment.