使用python调用外部的发送邮件的api接口发送邮件及excel附件
时间: 2023-05-15 07:08:00 浏览: 170
可以使用Python内置的smtplib库来调用外部的发送邮件的API接口,同时使用email库来构建邮件内容和附件。以下是一个示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 邮件发送者和接收者
sender = 'sender@example.com'
receiver = 'receiver@example.com'
# 邮件主题和正文
subject = '邮件主题'
text = '邮件正文'
# 构建邮件内容和附件
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
msg.attach(MIMEText(text))
# 添加Excel附件
with open('example.xlsx', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='xlsx')
attachment.add_header('Content-Disposition', 'attachment', filename='example.xlsx')
msg.attach(attachment)
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'username'
smtp_password = 'password'
smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.starttls()
smtp_conn.login(smtp_username, smtp_password)
smtp_conn.sendmail(sender, receiver, msg.as_string())
smtp_conn.quit()
```
对于中文加密的问题,可以使用Python内置的base64库来进行编码和解码。以下是一个示例代码:
```python
import base64
# 将中文字符串编码为base64格式
text = '中文加密'
encoded_text = base64.b64encode(text.encode('utf-8')).decode('utf-8')
print(encoded_text)
# 将base64格式的字符串解码为中文字符串
decoded_text = base64.b64decode(encoded_text.encode('utf-8')).decode('utf-8')
print(decoded_text)
```
阅读全文