import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.application import MIMEApplication# 发送方的邮箱账号和密码sender_email = 'your_qq_email@qq.com'sender_password = 'your_qq_password'# 接收方的邮箱账号receiver_email = 'receiver_email@example.com'# 创建一个带附件的邮件对象msg = MIMEMultipart()msg['Subject'] = '带附件的邮件'msg['From'] = sender_emailmsg['To'] = receiver_email# 添加邮件正文body = '这是一封带附件的邮件'msg.attach(MIMEText(body, 'plain'))# 添加附件filename = 'example.txt'with open(filename, 'rb') as f: attachment = MIMEApplication(f.read(), _subtype='txt') attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment)# 发送邮件with smtplib.SMTP_SSL('smtp.qq.com', 465) as smtp: smtp.login(sender_email, sender_password) smtp.sendmail(sender_email, receiver_email, msg.as_string())上述代码封装成函数
时间: 2023-10-04 08:07:11 浏览: 127
好的,可以封装成一个Python函数,如下所示:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def send_email_with_attachment(sender_email: str, sender_password: str, receiver_email: str, subject: str, body: str, filename: str):
# 创建一个带附件的邮件对象
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
# 发送邮件
with smtplib.SMTP_SSL('smtp.qq.com', 465) as smtp:
smtp.login(sender_email, sender_password)
smtp.sendmail(sender_email, receiver_email, msg.as_string())
```
这个函数接收发送方邮箱的账号和密码、接收方邮箱的账号、邮件主题、邮件正文和附件文件名作为参数,然后使用Python的`smtplib`和`email`模块发送带有附件的邮件。你可以调用这个函数来发送邮件,例如:
```python
sender_email = 'your_qq_email@qq.com'
sender_password = 'your_qq_password'
receiver_email = 'receiver_email@example.com'
subject = '带附件的邮件'
body = '这是一封带附件的邮件'
filename = 'example.txt'
send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, filename)
```
其中,`sender_email`和`sender_password`需要替换为你自己的QQ邮箱账号和密码,`receiver_email`为接收方的邮箱账号,`subject`为邮件主题,`body`为邮件正文,`filename`为附件的文件名。
阅读全文