python 发邮件加附件
时间: 2023-10-16 14:32:16 浏览: 86
好的,我可以为您提供一些参考代码。您需要使用Python中的smtplib模块和email模块。
以下是一个基本示例:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.utils import COMMASPACE
from email import encoders
import os
def send_mail(send_from, send_to, subject, text, files=[]):
'''
发送邮件并携带附件。
send_from: 发件人邮箱
send_to: 收件人邮箱
subject: 邮件主题
text: 邮件正文
files: 附件列表
'''
assert isinstance(send_to, list)
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Subject'] = subject
msg.attach(MIMEText(text, 'html'))
for file in files:
part = MIMEBase('application', "octet-stream")
with open(file, 'rb') as f:
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="{}"'.format(os.path.basename(file)))
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(send_from, 'your-password-here')
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
```
您需要将'your-password-here'替换为您的发件人帐户密码,并确认您的发件人帐户允许使用SMTP来发送电子邮件。
然后,您可以使用以下代码运行该函数:
```python
send_mail('sender@gmail.com', ['receiver1@gmail.com', 'receiver2@gmail.com'], 'Test email with attachment', 'This is a test email', ['test.txt', 'test.png'])
```
这将从'sender@gmail.com'发送一封包含'test.txt'和'test.png'两个附件的电子邮件,发送给'receiver1@gmail.com'和'receiver2@gmail.com'。
阅读全文