目录
目的:扫描目录并发送邮件
编写python代码,扫描指定的目录下的所有文件,将这些扫描的文本内容以邮件发形式送到指定邮箱(如:qq、gmail及 网易邮箱)
注意:
如果你选择使用QQ邮箱作为SMTP服务器,你需要确保你的QQ邮箱启用了SMTP服务,并且你有一个有效的授权码。
设置授权码请参考:简书:31.1企业级开发进阶3.1:发送电子邮件
代码示例:
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def send_email(sender_email, sender_password, receiver_email, subject, body, attachment_path=None):
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加正文
msg.attach(MIMEText(body, 'plain'))
if attachment_path:
# 添加附件
attachment = open(attachment_path, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {os.path.basename(attachment_path)}")
msg.attach(part)
# 发送邮件
server = smtplib.SMTP('smtp.qq.com', 587) # 请根据你的邮箱提供商和端口号进行修改
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
server.quit()
def scan_and_send_email(directory_path, sender_email, sender_password, receiver_email):
for filename in os.listdir(directory_path):
filepath = os.path.join(directory_path, filename)
if os.path.isfile(filepath):
subject = f"File: {filename}"
body = f"This is the content of {filename}."
send_email(sender_email, sender_password, receiver_email, subject, body, filepath)
# 填写你的邮箱和授权码
sender_email = '2297685232@qq.com'
sender_password = '****************' #自己的授权码
receiver_email = 'huoai823@gamil.com'
# 要扫描的目录路径
directory_path = 'D:/c语言'
scan_and_send_email(directory_path, sender_email, sender_password, receiver_email)
结果:
总结:
SMTPServerDisconnected错误:这个错误通常表示与SMTP服务器的连接被意外关闭。可能的解决方案包括检查网络连接是否正常、确认邮箱地址和密码是否正确以及确保SMTP服务器设置正确。
UnicodeDecodeError错误:这个错误可能会在尝试使用UTF-8或其他编码方式读取文件时出现,特别是当文件不是以该编码方式保存时。解决方法包括尝试不同的编码方式,如UTF-8或GBK。
文件路径问题:在扫描目录时,确保提供的目录路径是正确的,否则可能导致找不到文件或附件发送失败。
邮件发送失败:如果邮件发送失败,检查SMTP服务器设置和凭证
总的来说,当编写Python代码来扫描指定目录并发送邮件时,需要注意处理这些可能出现的问题,并适时添加调试信息以便更好地定位和解决问题。