[英]Editing the message in a Python email using smtplib
所以,我創建了這個簡單的程序,它每小時檢查一次我的研究數據是否有 nans。 它工作正常,但我想改進它發送給我的 email,當它找到一個 nan 時。 目前,我只能將它放在 email 我放在三個語音標記內的任何東西,像這樣message = """Missing data, yo."""
當它有一個nan時,我希望它給我日期時間和文件名。 我嘗試了以下方法,但它不起作用:
message = f"Hello, Cairan. {full_name} has missing data."
我已經嘗試過了,但它不起作用:
message = """Missing data """ + full_name
我不知道我在這里做錯了什么 - 請幫忙。 對於如何更改 email 的主題標題的任何建議,我也將不勝感激。
謝謝!
# -*- coding: utf-8 -*-
"""
This Python script was written for use on an Amazon EC2 server, with the Eltek GPRS Server running.
This code has a 60 minute loop, which:
1. Copies the data from its original location to a temporary 'checking' directory.
2. Imports the listed CSV files
3. Converts all 'No Data' into nans
4. Looks at the last 12 observations and checks if there is any nans - if there are any it will email an email address about the nans.
5. Loops over all files
6. Loops every hour
"""
# Import packages
import os #os
import fnmatch #fn match
import pandas as pd #pandas
import numpy as np #numpy
import sched #scheduler
import time # time
import smtplib #for email
import ssl #for email
from datetime import datetime #datetime
from termcolor import colored #for colouring text
from shutil import copyfile
# Scheduler
s = sched.scheduler(time.time, time.sleep)
# Email
user = '####@gmail.com' #email username (gmail tested and working)
sender = '####@gmail.com' #sendee email address
password = '####' #email password
port = 465 #port - 465 standard
recieve = '####'
context = ssl.create_default_context()
directory = "C:/EltekGateway/"
individual_files = "K01817-12158.csv", "K01830-12197.csv", "K01830-12200.csv"
files = "C:/EltekGateway/checking/K01817-12158.csv", "C:/EltekGateway/checking/K01830-12197.csv", "C:/EltekGateway/checking/K01830-12200.csv"
for full_name in individual_files:
checking_dir = directory + "checking/" + full_name
original_dir = directory + full_name
copyfile(original_dir, checking_dir)
print(original_dir, checking_dir)
def do_something(sc):
now = datetime.now()
print('<---------------------------------------------------------------------------------->')
print('Checking:' , len(files), 'datafiles.', 'Time now =', now)
for full_name in files:
df_tmp= pd.read_csv(full_name, skiprows = 5) # read csv to df_tmp
df_tmp.rename({'TX Channel': 'date'}, axis=1, inplace=True) # rename cols
df_tmp['date'] = pd.to_datetime(df_tmp['date'], errors='raise', dayfirst=True) # create datetime col
df_tmp = df_tmp.replace('No Data', np.nan) # Eltek 'No Data' to nan
df_check = df_tmp[-12:]
df_check = df_check.isnull().values.any()
# df_check = df_check.isna() # Check last observation to see if there is a nan
df_check_time = df_tmp.date.iloc[-1] # Store datetime for last obs
now = datetime.now()
date_string = df_check_time.strftime("%Y/%m/%d, %H:%M:%S")
# print(df_check) #checking loop
if df_check.any() == 0: # Check
print(date_string, full_name + colored(' - There is NO missing data','green'))
# print()
else:
print(date_string, full_name + colored(' - There IS missing data', 'red'))
message = """Missing data, yo."""
# message = f"Hello, Cairan. {full_name} has missing data."
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(sender, password)
server.sendmail(sender, recieve, message)
# print(df_tmp) #checking loop
# print(full_name) #checking loop
# print(df_check_time) #checking loop
print('<---------------------------------------------------------------------------------->')
s.enter(3600, 1, do_something, (sc,))
def main():
s.enter(3600, 1, do_something, (s,))
s.run()
if __name__ == "__main__":
main()
您的消息格式不正確。
您必須使用正確的 header 等來編寫它,如下所示:
message = """\
From: Robot <noreply@domain.com>
To: Persoon <persoon@gmail.com>
Subject: Something Fancy Happened!
Hi Persoon,
Your Thing caused Something Fancy!
Yours,
Robot.
"""
如果您不想手動構建消息,請查看https://docs.python.org/3/library/email.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.