Search code examples
python-2.7web2py

How to attach an uploaded file for e-mailing in web2py


All,

Python and web2py newbie here - I am trying to forward user input (e-mail address and a file) via e-mail, once a user has uploaded the information on a website. The user-provided-information is stored in a database but it is yet over my head to fetch the file from the database and forward it via e-mail. Any pointers much appreciated!

This is my controller action-

def careers():
    form = SQLFORM(db.cv_1, formstyle='bootstrap3_stacked')
    for label in form.elements('label'):
        label["_style"] = "display:none;"
    form.custom.submit.attributes['_value'] = 'Submit CV'
    if form.process().accepted:
        applicant = str(form.vars.email)
        mail.send(to=['[email protected]'], message= applicant + ' new CV', subject='CV submission', attachment=mail.Attachment('/path/to/file'))
    return dict(form=form)

This is the database model

db.define_table('cv_1', Field('email',
requires=IS_EMAIL(error_message='Please provide your e-mail'),
widget=widget(_placeholder='Your e-mail (required)',_readonly=False)),
Field('cv', 'upload', autodelete=True, requires=[IS_LENGTH(1048576,1024),
IS_UPLOAD_FILENAME(extension='pdf')]))

Solution

  • The transformed filename of the uploaded file will be in form.vars.cv (this is the value stored in the db.cv_1.cv field in the database). You can use that along with the field's .retrieve method to get either the full file path or the file object itself:

    original_filename, filepath = db.cv_1.cv.retrieve(form.vars.cv)
    mail.send(to=['[email protected]'], message=applicant + ' new CV',
              subject='CV submission',
              attachment=mail.Attachment(filepath, original_filename))