python一键发送--当前目录下文件到邮箱

"""

目标: 把当前目录下指定类型文件发送邮件

说明:

经常需要把一些小文件如*.txt,或者*.py,*.doc之类的文件发送到邮箱里供使用或备份

用qq邮箱客户端什么的实在是太麻烦了

只要把自己需要发送的文件全部放到当前目录下,代码就可以一键发送了.

本人纯编程小白,欢迎指教

"""

 

import smtplib
import email.mime.text
import email.mime.multipart

import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

 

# 1.取得当前目录下指定文件的文件名列表,缺省为txt

def get_type_file(keyword='.txt'): # 这里可以更改扩展名如.doc,.py,.zip等等
    # 打印当前的工作目录
    print("当前目录为: ",os.getcwd())

    # 列举当前工作目录下的文件名
    files=os.listdir()
    keyword=keyword
    filelist=[]

    i=0
    for file in files:
        if keyword in file:
            i=i+1
            print(i,file)
            filelist.append(file)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python自动化运维中,使用SMTplib库可以实现发送电子邮件的自动化功能。以下是一个基础的示例,展示如何通过SMTP协议发送一封带有附件的邮件: ```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders import os # 邮件设置 sender_email = 'your_email@example.com' sender_password = 'your_email_password' # 如果是SMTP应用密码,请使用 receiver_email = 'recipient_email@example.com' subject = 'Automated Email from Python' body = 'This is an automated message sent using Python.' attachment_path = 'path_to_your_attachment' # 例如 'document.pdf' # 创建邮件对象 msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = receiver_email msg['Subject'] = subject # 添加邮件正文 msg.attach(MIMEText(body, 'plain')) # 添加附件(如果有的话) with open(attachment_path, 'rb') as f: part = MIMEBase('application', 'octet-stream') part.set_payload(f.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attachment_path))) msg.attach(part) # 连接SMTP服务器 smtp_server = 'smtp.example.com' # 根据你的邮箱提供商填写 smtp_port = 587 # 或者465 for SSL/TLS (default for Gmail is 465) try: with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() # 如果需要加密连接,添加这行 server.login(sender_email, sender_password) server.sendmail(sender_email, receiver_email, msg.as_string()) print("Email sent successfully.") except Exception as e: print("Error sending email: ", str(e)) # 关闭连接 server.quit() ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值