PYTHON:发送带有每 15 分钟更新一次的附件的电子邮件

发布于 2025-01-20 01:02:27 字数 2588 浏览 0 评论 0原文

以下是我代码的一部分,每15分钟收集一次传感器的二氧化碳和温度读数是一段时间内。每15分钟将数据导出到新的CSV文件中。文件名每15分钟更改一次,因为文件名中需要的日期和时间戳记。

如果文件名称不断更改,可以使用Python发送带有CSV文件的电子邮件?

我在网上虚线下方找到了一个示例,但是在我的情况下,文件位置将每15分钟更改一次

for device in list_of_devices: 
        print (device)


for url_CO2 in list_of_urls_CO2:
        headers = CaseInsensitiveDict()
        headers['Accept'] = 'application/json'
        headers['Authorization'] = bearer_token

        resp_CO2 = requests.get(url_CO2, headers=headers)
        response_CO2.append(resp_CO2.text)

        print(resp_CO2.text)

for url_RT in list_of_urls_RT:
        headers = CaseInsensitiveDict()
        headers['Accept'] = 'application/json'
        headers['Authorization'] = bearer_token

        
        resp_RT = requests.get(url_RT, headers=headers)
        response_RT.append(resp_RT.text)

        print(resp_RT.text)

# importing pandas as pd  
import pandas as pd  

    
# dictionary of lists  
myDict = {'Device': list_of_devices, 'CO2 Level': response_CO2, 'Room Temperature': response_RT}  
    
df = pd.DataFrame(myDict) 

# saving the dataframe 
df.to_csv('test_{}.csv'.format(datetime.now().strftime("%Y-%m-%d %H.%M.%S")), index=False) 
----------------------------------------------------------------------------------------
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path

email = '[email protected]'
password = 'password'
send_to_email = '[email protected]'
subject = 'Town Farm Data Log'
message = 'Please see attached CO2 levels and Room Temperatures for Town Farm Classrooms'
file_location = 'C:\\Users\\You\\Desktop\\attach.txt'

msg = MIMEMultipart()
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject

msg.attach(MIMEText(message, 'plain'))

filename = os.path.basename(file_location)
attachment = open(file_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()

Below is a section of my code, it is in a while true loop to collect CO2 and Temperature readings from sensors every 15 minutes. It exports the data to a new CSV file every 15 minutes. The file name changes every 15 minutes as there is a date and time stamp required in the file name.

Can python be used to send an email with the CSV file attached if the file name is constantly changing?

I found the example below the dashed line online but the file location would be changing every 15 minutes in my case

for device in list_of_devices: 
        print (device)


for url_CO2 in list_of_urls_CO2:
        headers = CaseInsensitiveDict()
        headers['Accept'] = 'application/json'
        headers['Authorization'] = bearer_token

        resp_CO2 = requests.get(url_CO2, headers=headers)
        response_CO2.append(resp_CO2.text)

        print(resp_CO2.text)

for url_RT in list_of_urls_RT:
        headers = CaseInsensitiveDict()
        headers['Accept'] = 'application/json'
        headers['Authorization'] = bearer_token

        
        resp_RT = requests.get(url_RT, headers=headers)
        response_RT.append(resp_RT.text)

        print(resp_RT.text)

# importing pandas as pd  
import pandas as pd  

    
# dictionary of lists  
myDict = {'Device': list_of_devices, 'CO2 Level': response_CO2, 'Room Temperature': response_RT}  
    
df = pd.DataFrame(myDict) 

# saving the dataframe 
df.to_csv('test_{}.csv'.format(datetime.now().strftime("%Y-%m-%d %H.%M.%S")), index=False) 
----------------------------------------------------------------------------------------
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path

email = '[email protected]'
password = 'password'
send_to_email = '[email protected]'
subject = 'Town Farm Data Log'
message = 'Please see attached CO2 levels and Room Temperatures for Town Farm Classrooms'
file_location = 'C:\\Users\\You\\Desktop\\attach.txt'

msg = MIMEMultipart()
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject

msg.attach(MIMEText(message, 'plain'))

filename = os.path.basename(file_location)
attachment = open(file_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

メ斷腸人バ 2025-01-27 01:02:27

如果发送后不需要保留文件,则很容易这样做:

将发送电子邮件代码放入名为send_by_email的功能中,例如

,只需收集目标dir中的所有文件仅过滤CSV-S并一一发送它们(发送后不要忘记删除文件,以免在下一个迭代中进入永恒循环),

import os

mypath = '/tmp'                                         # define path to dir with your files
filenames = next(os.walk(mypath), (None, None, []))[2]  # list all files
csvs = [f for f in filenames if f.endswith('.csv')]     # fileter only .scv files

for filename in csvs:
    file_with_path = os.path.join(mypath, filename)
    send_by_email(file_with_path)
    os.remove(file_with_path)

如果您需要保留文件,只需将它们移至另一个DIR而不是删除。

If you don't need to keep your files after send, it's easy to do like this:

Put your sending email code into the function named send_by_email for example

Then just collect all the files in the target dir, filter only csv-s and send them one by one (don't forget to delete file after send not to get into eternal loop on next iteration)

import os

mypath = '/tmp'                                         # define path to dir with your files
filenames = next(os.walk(mypath), (None, None, []))[2]  # list all files
csvs = [f for f in filenames if f.endswith('.csv')]     # fileter only .scv files

for filename in csvs:
    file_with_path = os.path.join(mypath, filename)
    send_by_email(file_with_path)
    os.remove(file_with_path)

If you need to keep files, you can just move them into another dir instead of deleting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文