> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/python/cpython/llms.txt
> Use this file to discover all available pages before exploring further.

# email - Email and MIME Handling

> Email and MIME message handling

The `email` package provides tools for managing email messages, including MIME and other RFC 2822-based message documents.

## Module Import

```python theme={null}
from email.message import EmailMessage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import smtplib
```

## Creating Email Messages

### Simple Text Email

```python theme={null}
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'Hello'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg.set_content('This is the email body.')

print(msg.as_string())
```

### HTML Email

```python theme={null}
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'HTML Email'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'

msg.set_content('Plain text version')  # Fallback
msg.add_alternative("""
<html>
  <body>
    <h1>Hello!</h1>
    <p>This is an <b>HTML</b> email.</p>
  </body>
</html>
""", subtype='html')
```

### Email with Attachment

```python theme={null}
from email.message import EmailMessage
import os

msg = EmailMessage()
msg['Subject'] = 'File Attached'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg.set_content('Please find attached file.')

# Attach file
with open('document.pdf', 'rb') as f:
    file_data = f.read()
    file_name = os.path.basename('document.pdf')

msg.add_attachment(file_data, maintype='application', 
                   subtype='pdf', filename=file_name)
```

## Sending Email

### Using SMTP

```python theme={null}
from email.message import EmailMessage
import smtplib

# Create message
msg = EmailMessage()
msg['Subject'] = 'Test Email'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg.set_content('Test message body')

# Send via SMTP
with smtplib.SMTP('smtp.example.com', 587) as smtp:
    smtp.starttls()  # Enable encryption
    smtp.login('username', 'password')
    smtp.send_message(msg)

print('Email sent successfully')
```

### Using Gmail

```python theme={null}
from email.message import EmailMessage
import smtplib

msg = EmailMessage()
msg['Subject'] = 'Gmail Test'
msg['From'] = 'your-email@gmail.com'
msg['To'] = 'recipient@example.com'
msg.set_content('Email sent via Gmail')

# Send via Gmail SMTP
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login('your-email@gmail.com', 'your-app-password')
    smtp.send_message(msg)
```

## Parsing Email Messages

```python theme={null}
from email import message_from_string
from email.policy import default

email_text = """From: sender@example.com
To: recipient@example.com
Subject: Test

Email body content.
"""

msg = message_from_string(email_text, policy=default)

print(f"From: {msg['From']}")
print(f"To: {msg['To']}")
print(f"Subject: {msg['Subject']}")
print(f"Body: {msg.get_content()}")
```

## MIME Multipart

```python theme={null}
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

# Create multipart message
msg = MIMEMultipart()
msg['Subject'] = 'Multipart Message'
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'

# Add text part
text = MIMEText('This is the text part.', 'plain')
msg.attach(text)

# Add HTML part
html = MIMEText('<h1>HTML Part</h1>', 'html')
msg.attach(html)

# Add image
with open('image.jpg', 'rb') as f:
    img = MIMEImage(f.read())
    img.add_header('Content-Disposition', 'attachment', filename='image.jpg')
    msg.attach(img)
```

## Practical Example

### Email Utility Class

```python theme={null}
from email.message import EmailMessage
import smtplib
from pathlib import Path

class EmailSender:
    def __init__(self, smtp_server, smtp_port, username, password):
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.username = username
        self.password = password
    
    def send_email(self, to, subject, body, attachments=None, html=False):
        msg = EmailMessage()
        msg['Subject'] = subject
        msg['From'] = self.username
        msg['To'] = to
        
        if html:
            msg.set_content(body)  # Plain text fallback
            msg.add_alternative(body, subtype='html')
        else:
            msg.set_content(body)
        
        # Add attachments
        if attachments:
            for attachment in attachments:
                path = Path(attachment)
                with path.open('rb') as f:
                    msg.add_attachment(f.read(),
                                     maintype='application',
                                     subtype='octet-stream',
                                     filename=path.name)
        
        # Send email
        with smtplib.SMTP(self.smtp_server, self.smtp_port) as smtp:
            smtp.starttls()
            smtp.login(self.username, self.password)
            smtp.send_message(msg)

# Usage
sender = EmailSender('smtp.gmail.com', 587, 
                     'your-email@gmail.com', 'your-password')

sender.send_email(
    to='recipient@example.com',
    subject='Test Email',
    body='<h1>Hello!</h1><p>This is a test.</p>',
    html=True,
    attachments=['document.pdf', 'image.jpg']
)
```

<Tip>
  For Gmail, use an App Password instead of your regular password for better security.
</Tip>

<Warning>
  Never hardcode email credentials in your source code. Use environment variables or secure credential storage.
</Warning>

<CardGroup cols={2}>
  <Card title="smtplib" icon="envelope">
    SMTP protocol client
  </Card>

  <Card title="json" href="/library/json">
    JSON encoding/decoding
  </Card>
</CardGroup>
