python 通过 outlook 发送邮件及附件
时间: 2024-10-19 12:02:35 浏览: 19
在Python中,你可以使用`python-outlook`库结合`email`标准库来发送电子邮件,包括附件。以下是基本步骤:
首先,你需要安装所需的库,可以使用pip安装:
```bash
pip install python-dateutil pytz requests
pip install office365
```
然后,导入需要的模块并设置相关配置:
```python
from datetime import datetime
import os
import office365
from office365.runtime.auth.client_credential import ClientCredential
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
# Outlook客户端和邮箱信息
client_id = 'your_client_id'
client_secret = 'your_client_secret'
tenant = 'your_tenant.onmicrosoft.com'
username = 'your_email@your_domain.com'
password = 'your_password'
# 邮件内容和附件路径
to_address = 'recipient@example.com'
subject = 'Test Email with Attachment'
body = 'This is a test email sent using Python and Outlook.'
attachment_path = 'path_to_your_attachment.txt'
```
接下来创建连接并发送邮件:
```python
# 登录到Office 365
auth_manager = ClientCredential(tenant=tenant, client_id=client_id, client_secret=client_secret)
outlook = office365.OutlookServices(username, auth_manager)
# 创建MIMEMultipart对象作为邮件主体
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = to_address
msg['Subject'] = subject
msg.attach(MIMEText(body))
# 添加附件
with open(attachment_path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
# base64编码附件内容
encoders.encode_base64(part)
# 设置头信息
part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attachment_path)))
msg.attach(part)
# 将MIMEMultipart转换为字节串
msg_bytes = msg.as_string()
# 使用Outlook API发送邮件
try:
mail_folder = outlook.mail.create_item_body("IPM.Note")
mail_folder.body = msg_bytes
mail_folder.save()
print("Email sent successfully.")
except Exception as e:
print(f"Error sending email: {str(e)}")
阅读全文