Python3实现带附件的定时发送邮件功能
- 行业动态
- 2024-06-03
- 1
要实现带附件的定时发送邮件功能,我们需要使用Python的smtplib和email库,以下是详细步骤:
1、安装所需库
确保已经安装了Python的smtplib和email库,如果没有安装,可以使用以下命令安装:
“`
pip install securesmtplib
pip install email
“`
2、编写代码
导入所需库
“`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
import os
import schedule
import time
“`
设置邮箱账户信息
“`python
from_email = "your_email@example.com"
password = "your_password"
to_email = "recipient_email@example.com"
“`
创建邮件对象
“`python
msg = MIMEMultipart()
msg[‘From’] = from_email
msg[‘To’] = to_email
msg[‘Subject’] = "邮件主题"
“`
添加邮件正文
“`python
body = "邮件正文内容"
msg.attach(MIMEText(body, ‘plain’))
“`
添加附件
“`python
filename = "path/to/your/attachment"
attachment = open(filename, "rb")
part = MIMEBase(‘application’, ‘octetstream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘ContentDisposition’, "attachment; filename= %s" % filename)
msg.attach(part)
“`
发送邮件
“`python
def send_email():
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(from_email, password)
text = msg.as_string()
server.sendmail(from_email, to_email, text)
server.quit()
“`
设置定时任务
“`python
def job():
send_email()
print("邮件已发送")
schedule.every().day.at("10:30").do(job)
“`
运行定时任务
“`python
while True:
schedule.run_pending()
time.sleep(1)
“`
3、运行代码
将以上代码保存为一个.py文件,然后运行该文件,每天的10:30,程序将自动发送一封带附件的邮件。
本站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本站,有问题联系侵删!
本文链接:http://www.xixizhuji.com/fuzhu/204490.html