Bird
Raised Fist0
Flaskframework~20 mins

Email with attachments in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask Email Attachment Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What will this Flask email sending code do?
Consider this Flask snippet that sends an email with an attachment. What will be the result when this code runs?
Flask
from flask_mail import Mail, Message
from flask import Flask

app = Flask(__name__)
app.config.update(
    MAIL_SERVER='smtp.example.com',
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USERNAME='user@example.com',
    MAIL_PASSWORD='password'
)
mail = Mail(app)

with app.app_context():
    msg = Message('Hello', sender='user@example.com', recipients=['friend@example.com'])
    msg.body = 'See attached file.'
    with open('document.txt', 'rb') as f:
        msg.attach('document.txt', 'text/plain', f.read())
    mail.send(msg)
ASends an email without any attachment because attach() is called incorrectly.
BSends an email with subject 'Hello' and attaches 'document.txt' as a plain text file.
CRaises a FileNotFoundError because 'document.txt' does not exist in the code.
DSends an email but the attachment will be empty because the file is opened in text mode.
Attempts:
2 left
💡 Hint
Check how the file is opened and how attach() is used.
📝 Syntax
intermediate
1:30remaining
Identify the syntax error in this Flask email attachment code
Which option shows the correct way to attach a PDF file in Flask-Mail? The code snippet is: msg = Message('Report', sender='me@example.com', recipients=['you@example.com']) msg.body = 'Please find the report attached.' with open('report.pdf', 'rb') as pdf: msg.attach('report.pdf', 'application/pdf', pdf.read()) Which option has a syntax error?
Amsg.attach('report.pdf', 'application/pdf', pdf.read)
Bmsg.attach('report.pdf', 'application/pdf', pdf.read())
C))(daer.fdp ,'fdp/noitacilppa' ,'fdp.troper'(hcatta.gsm
Dsg.attach('report.pdf', 'application/pdf', pdf.read())
Attempts:
2 left
💡 Hint
Look carefully at how the file content is passed to attach().
🔧 Debug
advanced
2:30remaining
Why does this Flask email with attachment fail to send?
This Flask code tries to send an email with an attachment but fails silently (no error, no email sent). What is the most likely cause? app.config.update( MAIL_SERVER='smtp.example.com', MAIL_PORT=587, MAIL_USE_TLS=True, MAIL_USERNAME='user@example.com', MAIL_PASSWORD='password' ) mail = Mail(app) with app.app_context(): msg = Message('Data', sender='user@example.com', recipients=['friend@example.com']) msg.body = 'Attached data file.' with open('data.csv', 'rb') as f: msg.attach('data.csv', 'text/csv', f.read()) mail.send(msg) What is the most probable reason no email is sent?
AThe MAIL_USE_TLS should be False to send attachments.
BThe app context is missing, so mail.send() does nothing.
CThe MAIL_PORT 587 requires MAIL_USE_TLS=True, which is set correctly, so no issue here.
DThe MAIL_USERNAME and MAIL_PASSWORD are likely incorrect or SMTP server rejects authentication silently.
Attempts:
2 left
💡 Hint
Check SMTP credentials and server response.
❓ state_output
advanced
2:00remaining
What is the content type of the attachment in this Flask email?
Given this code snippet: msg = Message('Invoice', sender='me@example.com', recipients=['client@example.com']) msg.body = 'Invoice attached.' with open('invoice.xlsx', 'rb') as file: msg.attach('invoice.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file.read()) What will be the MIME type of the attached file in the sent email?
Aapplication/octet-stream
Bapplication/vnd.ms-excel
Capplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Dtext/plain
Attempts:
2 left
💡 Hint
Check the second argument of attach() method.
🧠 Conceptual
expert
3:00remaining
Which Flask-Mail method ensures attachments are included in multipart emails?
In Flask-Mail, when sending an email with attachments, which method or property ensures the email is sent as a multipart message so attachments are included properly?
AUsing msg.attach() automatically converts the email to multipart if needed.
BYou must set msg.content_subtype = 'multipart' manually before attaching files.
CAttachments require setting msg.is_multipart = True explicitly before sending.
DFlask-Mail does not support multipart emails with attachments.
Attempts:
2 left
💡 Hint
Check Flask-Mail documentation on how attachments affect email format.

Practice

(1/5)
1. What is the main purpose of the attach() method in Flask-Mail when sending emails?
easy
A. To set the email subject
B. To configure the mail server settings
C. To specify the recipient's email address
D. To add files as attachments to the email

Solution

  1. Step 1: Understand Flask-Mail's attach() method

    The attach() method is designed to add files as attachments to an email message.
  2. Step 2: Differentiate from other email settings

    Setting subject, recipient, or server configuration are done by other methods or configurations, not attach().
  3. Final Answer:

    To add files as attachments to the email -> Option D
  4. Quick Check:

    attach() adds files to email [OK]
Hint: attach() means adding files to email [OK]
Common Mistakes:
  • Confusing attach() with setting email subject
  • Thinking attach() configures server
  • Using attach() to set recipient address
2. Which of the following is the correct way to attach a file named report.pdf using Flask-Mail's attach() method?
easy
A. msg.attach('report.pdf', 'application/pdf', open('report.pdf', 'r').read())
B. msg.attach('report.pdf', 'application/pdf', open('report.pdf', 'rb').read())
C. msg.attach('report.pdf', 'text/plain', open('report.pdf', 'rb').read())
D. msg.attach('report.pdf', 'application/pdf', 'report.pdf')

Solution

  1. Step 1: Check file mode for reading attachments

    Files must be read in binary mode ('rb') to attach correctly, especially PDFs.
  2. Step 2: Verify MIME type correctness

    The MIME type for PDF files is 'application/pdf', so it must match the file type.
  3. Final Answer:

    msg.attach('report.pdf', 'application/pdf', open('report.pdf', 'rb').read()) -> Option B
  4. Quick Check:

    Binary read + correct MIME = msg.attach('report.pdf', 'application/pdf', open('report.pdf', 'rb').read()) [OK]
Hint: Read files in 'rb' mode and use correct MIME type [OK]
Common Mistakes:
  • Reading file in text mode ('r') instead of binary ('rb')
  • Using wrong MIME type like 'text/plain' for PDFs
  • Passing filename string instead of file content
3. Given the code snippet below, what will be the output behavior when sending the email?
from flask_mail import Message
msg = Message('Hello', sender='me@example.com', recipients=['you@example.com'])
with open('image.png', 'rb') as f:
    msg.attach('image.png', 'image/png', f.read())
mail.send(msg)
medium
A. The code will raise a FileNotFoundError if 'image.png' is missing
B. The email will send but without any attachments
C. The email will be sent with 'image.png' attached correctly
D. The code will raise a TypeError due to wrong attach parameters

Solution

  1. Step 1: Analyze file opening behavior

    The code opens 'image.png' in binary mode. If the file does not exist, Python raises FileNotFoundError.
  2. Step 2: Consider normal execution

    If the file exists, the email sends with the attachment. If missing, the error stops execution.
  3. Final Answer:

    The code will raise a FileNotFoundError if 'image.png' is missing -> Option A
  4. Quick Check:

    Missing file causes FileNotFoundError [OK]
Hint: Missing file causes FileNotFoundError, not silent send [OK]
Common Mistakes:
  • Assuming email sends without attachment if file missing
  • Thinking attach() parameters cause TypeError here
  • Ignoring file existence check
4. Identify the error in the following Flask-Mail code snippet that tries to attach a text file:
msg = Message('Report', sender='me@example.com', recipients=['you@example.com'])
file = open('report.txt', 'r')
msg.attach('report.txt', 'text/plain', file.read())
file.close()
mail.send(msg)
medium
A. The attach method requires a filename only, not content
B. The MIME type 'text/plain' is incorrect for text files
C. File should be opened in binary mode ('rb') to attach properly
D. The file should be closed after sending the email

Solution

  1. Step 1: Check file open mode for attachments

    Even for text files, Flask-Mail expects file content in bytes, so 'rb' mode is recommended.
  2. Step 2: Validate MIME type and file handling

    'text/plain' is correct for text files, and closing file before sending is fine.
  3. Final Answer:

    File should be opened in binary mode ('rb') to attach properly -> Option C
  4. Quick Check:

    Always open files in 'rb' for attach() [OK]
Hint: Open files in 'rb' mode even for text attachments [OK]
Common Mistakes:
  • Opening files in text mode ('r') causes attachment issues
  • Misunderstanding MIME type for text files
  • Closing file after reading is correct, not an error
5. You want to send an email with multiple attachments using Flask-Mail. Which approach correctly attaches both a PDF and an image file before sending?
msg = Message('Files', sender='me@example.com', recipients=['you@example.com'])
# Attach PDF
with open('doc.pdf', 'rb') as pdf:
    msg.attach('doc.pdf', 'application/pdf', pdf.read())
# Attach Image
with open('photo.jpg', 'rb') as img:
    msg.attach('photo.jpg', 'image/jpeg', img.read())
mail.send(msg)
hard
A. This code correctly attaches both files and sends the email
B. You must call mail.send() after each attach() call separately
C. Files must be concatenated into one before attaching
D. attach() only supports one file per email, so this fails

Solution

  1. Step 1: Review multiple attach() calls

    Flask-Mail allows multiple attach() calls on the same Message object to add multiple files.
  2. Step 2: Confirm file reading and sending

    Files are read in binary mode with correct MIME types, and mail.send() is called once after all attachments.
  3. Final Answer:

    This code correctly attaches both files and sends the email -> Option A
  4. Quick Check:

    Multiple attach() calls before one send() is correct [OK]
Hint: Call attach() multiple times, then send once [OK]
Common Mistakes:
  • Calling mail.send() multiple times unnecessarily
  • Trying to merge files before attaching
  • Believing attach() supports only one file
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard