Email mime multipart python
A classic topic!
To send a MIME multipart email using Python, you can use the email
and mimetypes
modules. Here's an example:
import email
import mimetypes
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# Create a multipart message
msg = MIMEMultipart()
# Add a text part
text_part = MIMEText("Hello, world!")
msg.attach(text_part)
# Add an attachment (e.g., a PDF file)
attachment = open("example.pdf", "rb")
attachment_part = MIMEApplication(attachment.read(), "pdf")
attachment_part.add_header("Content-Disposition", "attachment", filename="example.pdf")
msg.attach(attachment_part)
# Add another attachment (e.g., an image file)
image_attachment = open("example.png", "rb")
image_attachment_part = MIMEApplication(image_attachment.read(), "png")
image_attachment_part.add_header("Content-Disposition", "attachment", filename="example.png")
msg.attach(image_attachment_part)
# Set the sender and recipient
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = "Example MIME Multipart Email"
# Send the email using your preferred email library or service
# For example, using smtplib:
server = smtplib.SMTP("your_smtp_server")
server.sendmail("[email protected]", "[email protected]", msg.as_string())
server.quit()
This code creates a MIMEMultipart
message and adds three parts:
- A text part with the content "Hello, world!".
- An attachment (a PDF file) with the name "example.pdf".
- Another attachment (an image file) with the name "example.png".
The MIMEApplication
class is used to create the attachment parts, and the add_header
method is used to set the Content-Disposition
header to specify the attachment's filename.
Finally, the msg
object is sent using your preferred email library or service. In this example, we use smtplib
to send the email.
Note that this is just a basic example, and you may need to add additional headers or modify the code to suit your specific use case.