python 自动化办公 - 邮件自动发送
获取授权码
设置>账户>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
选择开启
邮件的自动发送只依赖python自带类库就能解决:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText
- 连接邮箱服务器
smtplib.SMTP_SSL(服务器地址,邮箱服务端口) — 连接邮箱服务器并返回一个连接对象
connect = smtplib.SMTP_SSL('smtp.qq.com', 465,'utf-8')
-
登录邮箱 连接对象.login(账号,密码)
connect.login('******@qq.com','授权码')
- 准备邮件
email = MIMEMultipart()
email['Subject'] = Header('邮件自动发送!','utf-8').encode()
email['To'] = '*****@qq.com'
email['From'] = '*@qq.com<1016226614@qq.com>'
- 添加正文
MIMEText(文字内容,类型,编码方式) 类型 — plain(普通文字)、HTML(超文本)
text = MIMEText('Hello??','plain','utf-8')
email.attach(text)
-
通过连接发送邮件 连接对象.sendmail(发件人,收件人,邮件对象.as_string())
connect.sendmail('***@qq.com','***@qq.com',email.as_string())
connect.quit()
附件发送
连接邮箱服务器登录同上;不再赘述
1、打开图片读取图片二进制数据
image_data = open('files/image/1.png','rb').read()
2、创建图片对象
image = MIMEImage(image_data)
3、设置图片为附件
image['Content-Disposition'] = 'attachment; filename="文件名"'
4、将附件添加到邮件对象中
email.attach(image)
xlsx文件发送:
file_data = open('files/task.xlsx', 'rb').read()
file = MIMEText(file_data,'base64','utf-8')
file['Content-Disposition'] = 'attachment; filename="Task.xlsx"'
email.attach(file)
发送超文本内容
content = open('files/content.html',encoding='utf-8').read()
text = MIMEText(content,'html','utf-8')
email.attach(text)
all_images = os.listdir('files/img')
for img in all_images:
image_data = open(f'files/img/{img}','rb').read()
image = MIMEImage(image_data)
image_id = img.split('.')[0]
image.add_header('Content-ID',f'<{image_id}>')
email.attach(image)
发送结果: HTML文件中本地文件路径书写格式:
文件批量发送
all_files = os.listdir('files/otherfiles')
for file in all_files:
txt_data = open(f'files/otherfiles/{file}', 'rb').read()
txt = MIMEText(txt_data, 'base64', 'utf-8')
txt_name = file.split('.')[0]
txt_last = file.split('.')[1]
print(txt_last)
txt['Content-Disposition'] = f'attachment; filename="{txt_name}.{txt_last}"'
email.attach(txt)
源码及HTML文件授权码获取及详细教程:链接: https://pan.baidu.com/s/1_LvGREHMpNg0KG35fU6D9g 提取码: v648
|