python发送带附件的邮件
时间: 2023-07-21 08:06:15 浏览: 46
你可以使用 Python 的 smtplib 和 email 库来发送带附件的邮件。下面是一个示例代码:
```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
# 设置发件人、收件人和邮件内容
from_address = "your_email@gmail.com"
to_address = "recipient_email@gmail.com"
subject = "带附件的邮件"
message = "这是一封带附件的邮件,请查收!"
# 创建一个 MIMEMultipart 对象
msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = subject
# 添加邮件内容
msg.attach(MIMEText(message, 'plain'))
# 添加附件
filename = "attachment.txt"
attachment = open(filename, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
# 发送邮件
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_address, "your_password")
text = msg.as_string()
server.sendmail(from_address, to_address, text)
server.quit()
```
在上面的代码中,你需要将 `your_email@gmail.com` 替换为发件人的邮箱,`recipient_email@gmail.com` 替换为收件人的邮箱,以及 `your_password` 替换为发件人邮箱的密码。你还需要将附件文件的路径和文件名替换为你想要发送的附件。
请注意,这个示例代码使用的是 Gmail 的 SMTP 服务器。如果你使用其他邮箱提供商,请相应地更改服务器的主机名和端口号。
希望这可以帮助到你!如有任何疑问,请随时提问。