用python发带附件的邮件_使用Python发送带附件的电子邮件

我正在尝试编写一个Python脚本,它将:

1在一天中的预定时间运行。

2将收集特定目录(例如C:\myFiles)中的任何文件(以.mobi格式),并将其作为附件发送到特定的电子邮件地址(电子邮件id保持不变)。

三。C:\myFiles目录中的文件将随着时间的推移而不断变化(因为我有另一个脚本,它对这些文件执行一些归档操作并将它们移到不同的文件夹中)。然而,新的文件将继续出现。我有一个if条件检查开始,以确定文件是否存在(只有这样它才会发送电子邮件)。在

我无法检测到任何mobi文件(使用*.mobi不起作用)。如果我显式地添加文件名,那么我的代码可以工作,否则就不行

如何使代码在运行时自动检测.mobi文件?

以下是我目前所掌握的情况:import os

# Import smtplib for the actual sending function

import smtplib

import base64

# For MIME type

import mimetypes

# Import the email modules

import email

import email.mime.application

#To check for the existence of .mobi files. If file exists, send as email, else not

for file in os.listdir("C:/Users/srayan/OneDrive/bookManager/EmailSenderModule"):

if file.endswith(".mobi"):

# Create a text/plain message

msg = email.mime.Multipart.MIMEMultipart()

#msg['Subject'] = 'Greetings'

msg['From'] = 'sender@gmail.com'

msg['To'] = 'receiver@gmail.com'

# The main body is just another attachment

# body = email.mime.Text.MIMEText("""Email message body (if any) goes here!""")

# msg.attach(body)

# File attachment

filename='*.mobi' #Certainly this is not the right way to do it?

fp=open(filename,'rb')

att = email.mime.application.MIMEApplication(fp.read(),_subtype="mobi")

fp.close()

att.add_header('Content-Disposition','attachment',filename=filename)

msg.attach(att)

server = smtplib.SMTP('smtp.gmail.com:587')

server.starttls()

server.login('sender@gmail.com','gmailPassword')

server.sendmail('sender@gmail.com',['receiver@gmail.com'], msg.as_string())

server.quit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值