Sending emails with attachments lets you share files like pictures or documents easily through your app.
0
0
Email with attachments in Flask
Introduction
You want to send a report PDF from your web app to users.
You need to email images uploaded by users to an admin.
Your app should send invoices as attached files automatically.
You want to share logs or data files via email for support.
Syntax
Flask
from flask_mail import Mail, Message mail = Mail(app) msg = Message(subject, sender=sender_email, recipients=[receiver_email]) msg.body = 'Email text here' msg.attach(filename, content_type, data) mail.send(msg)
Use msg.attach() to add files. It needs the filename, content type (like 'application/pdf'), and the file data in bytes.
Make sure Flask-Mail is configured with your email server settings before sending.
Examples
Attach a PDF file named 'report.pdf' by reading it in binary mode.
Flask
msg.attach('report.pdf', 'application/pdf', open('report.pdf', 'rb').read())
Attach an image using image data stored in a variable.
Flask
msg.attach('image.png', 'image/png', image_data)
Attach a simple text file created from bytes directly.
Flask
msg.attach('notes.txt', 'text/plain', b'Hello, this is a text file')
Sample Program
This Flask app sends an email with a text file attached when you visit /send-email. It reads 'example.txt' and attaches it to the email.
Flask
from flask import Flask from flask_mail import Mail, Message app = Flask(__name__) # Configure mail server (example with Gmail SMTP) app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 587 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = 'your_email@gmail.com' app.config['MAIL_PASSWORD'] = 'your_password' mail = Mail(app) @app.route('/send-email') def send_email(): msg = Message('Hello with Attachment', sender='your_email@gmail.com', recipients=['friend@example.com']) msg.body = 'Hi there! Please find the attached file.' with open('example.txt', 'rb') as f: msg.attach('example.txt', 'text/plain', f.read()) mail.send(msg) return 'Email sent with attachment!' if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Always keep your email credentials safe and do not hardcode them in production.
Attachments must be read in binary mode to avoid corruption.
Test sending emails with small files first to confirm setup works.
Summary
Use Flask-Mail's attach() method to add files to emails.
Configure your mail server settings before sending emails.
Read files in binary mode to attach them correctly.