pycharm 发送带图片的邮件
时间: 2024-11-09 13:31:00 浏览: 6
在PyCharm中发送带图片的邮件通常需要结合smtplib和email库,这两个都是Python标准库的一部分。以下是简单的步骤:
1. 首先导入所需的库:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
```
2. 创建MIMEMultipart对象作为邮件的基础结构:
```python
msg = MIMEMultipart()
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient_email@example.com'
msg['Subject'] = '带有图片的邮件'
```
3. 添加HTML文本内容(包括图片):
```python
body = """
<html>
<body>
<p>这是一封包含图片的邮件</p>
<img src="cid:image1">
</body>
</html>
"""
part = MIMEText(body, 'html')
msg.attach(part)
```
4. 添加图片数据作为附件:
```python
with open('image.jpg', 'rb') as f:
img_data = f.read()
image_part = MIMEBase('image', 'jpeg')
image_part.set_payload(img_data)
encoders.encode_base64(image_part)
image_part.add_header('Content-Disposition', 'attachment', filename='image.jpg')
msg.attach(image_part)
```
5. 使用SMTP服务器发送邮件:
```python
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'your_username'
password = 'your_password'
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
text = msg.as_string()
server.sendmail(msg['From'], msg['To'], text)
server.quit()
```
记得替换上述示例中的`your_email@example.com`, `recipient_email@example.com`, `your_username`, 和 `your_password`等为实际的邮箱地址和密码。
阅读全文