0

In my python django project i use this two method for send html email:

def send_html_email(to_list, subject, template_name, context, sender=settings.DEFAULT_FROM_EMAIL):
    msg_html = render_to_string(template_name, context)
    msg = EmailMessage(subject=subject, body=msg_html,
                   from_email=sender, to=to_list)
    msg.content_subtype = "html"  # Main content is now text/html
    return msg.send()


def emailsend(l_sender, l_lic, t_name='consok'):

    if t_name == 'lavoraok':
        templ = 'lavora_ok.html'
        ttitle = 'test: Nuova candidatura da sito web'
    elif t_name == 'lavoraok_cli':
        templ = 'lavora_ok_cli.html'
        ttitle = 'test: Nuova candidatura da sito web'
    else:
        templ = 'cons_del.html'
        ttitle = 'test: Appuntamento cancellato'

    context = {
        'news': 'test consulenza',
        'lic': l_lic
    }

    try:
        send_html_email(l_sender, ttitle, templ, context,
                    sender='test@prova.com')
    except Exception as e:
        print('Email send error: ', e)

all woks well, but now in my new form i got a field for attach a file to send via email. How can i implement my defs for attach file to email?

So many thanks in advance

Manuel Santi
  • 1,106
  • 17
  • 46

1 Answers1

2

According to the documentation for EmailMessage objects, you can add an attachments parameter:

attachments: A list of attachments to put on the message. These can be either MIMEBase instances, or (filename, content, mimetype) triples.

So, one example using this approach might be:

attachments = []  # list of attachments
for filename in filenames:  # filenames is the list of filenames corresponding to your attachments
    content = open(filename, "rb").read()
    attachment = (filename, content, "mimetype")  # replace mimetype with actual mimetype
    attachments.append(attachment)

# Send the email with attachments
email = EmailMessage("Subject", "Body", "from@email.com", ["to@email.com"], attachments=attachments)
email.send()

You can also call the attach() function on an EmailMessage object, which will create a new file attachment and add it to the message, or attach_file() to attach a file from the file system.

The latter two options are described in more detail in the aforementioned documentation.

JoshG
  • 6,472
  • 2
  • 38
  • 61