# Sending Django Emails

# Send Mail Imports

Take what you need 🎉 💯

from django.conf import settings
from django.core.mail import EmailMultiAlternatives, get_connection, send_mail
from django.template.loader import get_template
from django.template import Context
from django.contrib.auth.models import User
from .models import *
import requests

from django.core.mail.message import EmailMessage

# Dynamic SMTP Settings

Send email with dynamic settings and connection

def sendTestingEmail(host, port, username, password, use_tls, from_email, to_email):
    subject = 'The Subject of the mail'
    body = """
    Hello,

    Content of the mail

    Regards,
    """
    connection = get_connection(host=host, port=port, username=username, password=password, use_tls=use_tls)
    EmailMessage(subject, body, from_email, [to_email], connection=connection).send()
    connection.close()

# Send Email with EmailMultiAlternatives

If you want to send HTML emails


def sendAnEmail(to_email):
    from_email = settings.EMAIL_HOST_USER
    subject = 'Subject of your mail'

    text_content = """
    Hello,

    Content of the mail

    Regards,
    """


    html_c = get_template('email/email-template.html')
    d = {}
    d['variable1'] = 'Variable1'
    html_content = html_c.render(d)

    msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
    msg.attach_alternative(html_content, 'text/html')
    msg.send()

# Send an email with an attachment

If you need to attach a document to the email.

def emailMinutesMeeting(firstName, message, to_email, filename, pdf_location):
    from_email = settings.EMAIL_HOST_USER
    subject = 'Subject of the email'

    text_content = """

    Dear {},

    {}

    regards,
    """. format(firstName, message)


    html_c = get_template('email/email-template.html')
    d = {}
    d['firstName'] = firstName
    d['message'] = message
    html_content = html_c.render(d)

    msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
    msg.attach_alternative(html_content, 'text/html')

    file_data = open(pdf_location, 'rb')
    msg.attach(filename, file_data.read(), "application/pdf")

    file_data.close()
    msg.send()