GVKun编程网logo

即使我的文件有我要查找的字符串,我仍然通过 python 收到错误电子邮件

8

在本文中,我们将为您详细介绍即使我的文件有我要查找的字符串,我仍然通过python收到错误电子邮件的相关知识,此外,我们还会提供一些关于PythonGmailAPI:如何批量下载电子邮件附件和电子邮件

在本文中,我们将为您详细介绍即使我的文件有我要查找的字符串,我仍然通过 python 收到错误电子邮件的相关知识,此外,我们还会提供一些关于Python Gmail API:如何批量下载电子邮件附件和电子邮件?、Python SQL 脚本 - 如何发送有错误的电子邮件、python – 使用Bluehost电子邮件服务器的Django电子邮件配置、Python 教程 (7)—— 一文弄懂 Python 字符串操作 (上)| 字符串查找 | 字符串分割 | 字符串拼接 | 字符串替换的有用信息。

本文目录一览:

即使我的文件有我要查找的字符串,我仍然通过 python 收到错误电子邮件

即使我的文件有我要查找的字符串,我仍然通过 python 收到错误电子邮件

如何解决即使我的文件有我要查找的字符串,我仍然通过 python 收到错误电子邮件?

即使我的 Rout 文件的 end_str 格式完全相同,我仍然收到电子邮件警报。它根本不应该向我发送电子邮件,因为从技术上讲没有错误。为什么会发生这种情况?

import pandas as pd
import smtplib
from email.message import EmailMessage

df = pd.read_fwf(r''Service-Now-Data.Rout'',header=None)
end_str = ''#--- END ---------------------------------------------------------------------------------------------------''
cols_to_check = ["0"]


def email_alert(subject,body,to):
    msg = EmailMessage()
    msg.set_content(body)
    msg[''subject''] = subject
    msg[''to''] = to
        
    user = "DataScienceScriptAlerts@cfi.com"
    msg[''from''] = user

        
    server = smtplib.SMTP("pmixx36.corp.hhhegroup.com",2525)
    server.starttls()
    #server.login(user,password)
    server.send_message(msg)
        
    server.quit()

if __name__ == ''__main__'':

    for col in cols_to_check:
        if not df[0].str.contains(end_str).any():
            body = "There Service-Now-Data.R script in xxx had errors on the last execution" + col + "."
            print(body)
            email_alert("Service-Now-Data failure alert","jtl.t@cfi.com")
        

df的内容明明有end_str

df[0]
Out[3]: 
0      R version 4.0.4 (2021-02-15) -- "Lost Library ...
1      copyright (C) 2021 The R Foundation for Statis...
2              Platform: x86_64-w64-mingw32/x64 (64-bit)
3      R is free software and comes with ABSOLUTELY N...
397                                                    >
398    > #--- END -----------------------------------...
399                                                    >
400                                        > proc.time()
401                                 user  system elapsed
402                                76.10    4.92  374.51
Name: 0,Length: 403,dtype: object

正如你所看到的,在 df 中存在 end_str 并且它仍然在下面说 false

print(df[0].str.contains(end_str))
0      False
397    False
398    False
399    False
400    False
401    False
402    False
Name: 0,dtype: bool

解决方法

我无法重现您的错误

import pandas as pd
import numpy as np
end_str = ''#--- END ---------------------------------------------------------------------------------------------------''
df = pd.DataFrame([end_str])
print(df[0].str.contains(end_str))
0    True
Name: 0,dtype: bool

这意味着您的 end_str 与文件中包含的内容不匹配

我建议在 rout 文件中仔细检查您的结束字符串,以确保没有任何中断。或者将字符串缩短为''END''

import pandas as pd
import numpy as np
end_str = ''END''
df = pd.DataFrame([''#--- END ---------------------------------------------------------------------------------------------------''])
print(df[0].str.contains(end_str))
0    True
Name: 0,dtype: bool

Python Gmail API:如何批量下载电子邮件附件和电子邮件?

Python Gmail API:如何批量下载电子邮件附件和电子邮件?

如何解决Python Gmail API:如何批量下载电子邮件附件和电子邮件??

我有以下代码,用于下载 Gmail 电子邮件及其附件。它返回它的附件。

    def gmailAPIDownloadAttachments(self,messageID,userID="me"):
        try:
            service = self.gmailAPIService
            self.GLogger.info("Attempting to download attachments from messageID (" +str(messageID)+ ")")
            message = self.gmailAPIGetFullMessage(messageID,userID=userID)
            if message is False:
                self.GLogger.error("Failed to extract message (" +str(messageID)+ ") for downloading attachments")
                return False
            attachmentList = list()
            payload = message[''payload'']
            if ''parts'' in payload:
                parts = payload[''parts'']
                for part in parts:
                    if part[''filename'']:
                        if ''data'' in part[''body'']:
                            data = part[''body''][''data'']
                        else:
                            att_id = part[''body''][''attachmentId'']
                            att = service.users().messages().attachments().get(userId=userID,messageId=messageID,id=att_id).execute()
                            data = att[''data'']
                        file_data = base64.urlsafe_b64decode(data.encode(''UTF-8''))
                        filename = part[''filename'']
                        extSearch = filename.find(''.'')
                        if extSearch == -1:
                            ext = ""
                            partFileName = filename[0:extSearch]
                        else:
                            ext = filename[extSearch+1:]
                            partFileName = filename[0:extSearch]

                        theAttachment = Attachment(filename,partFileName,ext,file_data)
                        attachmentList.append(theAttachment)

            self.GLogger.info("Successfully downloaded attachments from messageID (" +str(messageID)+ ")")
            return(attachmentList)
        except:
            self.GLogger.error("Encountered an error while attempting to download email attacments from messageID (" +str(messageID)+ ")")
            tb = traceback.format_exc()
            self.GLogger.exception(tb)
            return False

我了解如何将获取消息转换为批处理。例如,这是批量获取消息的方式:

from apiclient.http import BatchHttpRequest
import json

batch = BatchHttpRequest()

#assume we got messages from Gmail query API
for message in messages:
    batch.add(service.users().messages().get(userId=''me'',id=message[''id''],format=''raw''))
batch.execute()
for request_id in batch._order:
    resp,content = batch._responses[request_id]
    message = json.loads(content)
    #handle your message here,like a regular email object

然而,附件方面似乎有逻辑和其他可能的提取,例如在这一部分:

att_id = part[''body''][''attachmentId'']
att = service.users().messages().attachments().get(userId=userID,id=att_id).execute()
data = att[''data'']

如何有效地批量获取邮件及其附件?我希望能够一次快速获取多封电子邮件。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Python SQL 脚本 - 如何发送有错误的电子邮件

Python SQL 脚本 - 如何发送有错误的电子邮件

查看此答案 https://stackoverflow.com/a/42143703/1525867 解释如何捕获 pyodbc 特定错误(我个人使用 https://sendgrid.com/ 发送电子邮件)

python – 使用Bluehost电子邮件服务器的Django电子邮件配置

python – 使用Bluehost电子邮件服务器的Django电子邮件配置

我是Bluehost和Django的新手,我正在尝试使用Django在我的Bluehost服务器上设置“通过电子邮件重置密码”功能.我在设置主机和端口号时尝试了不同的组合,但由于某种原因它从未起作用.所以这就是我所拥有的:(我目前只在我的本地计算机上工作.)

在我可以配置我的电子邮件帐户的Bluehost网站上,它列出:

手动设置

>邮件服务器用户名:admin my_host.com
>接收邮件服务器:mail.my_host.com
>接收邮件服务器:(SSL)Box664.bluehost.com
>发送邮件服务器:mail.my_host.com(服务器要求身份验证)端口26
>发送邮件服务器:(SSL)Box664.bluehost.com(服务器要求身份验证)端口465
>支持的传入邮件协议:POP3,POP3S(SSL / TLS),IMAP,IMAPS(SSL / TLS)
>支持的传出邮件协议:SMTP,SMTPS(SSL / TLS)

在settings.py中,我将电子邮件配置为:(我将列出两个组合和相应的错误消息)

组合1

DEFAULT_FROM_EMAIL  = 'admin@my_host.com'
SERVER_EMAIL = 'admin@my_host.com'
EMAIL_USE_TLS   = False
EMAIL_HOST      = 'Box664.bluehost.com'
EMAIL_HOST_PASSWORD = 'my_email_password'
EMAIL_HOST_USER = 'admin+my_host.com'
EMAIL_PORT      = 465
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

错误消息:异常值:连接意外关闭

组合2

DEFAULT_FROM_EMAIL  = 'admin@my_host.com'
SERVER_EMAIL = 'admin@my_host.com'
EMAIL_USE_TLS   = True
EMAIL_HOST      = 'mail.my_host.com'
EMAIL_HOST_PASSWORD = 'my_email_password'
EMAIL_HOST_USER = 'admin+my_host.com'
EMAIL_PORT      = 26
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

错误消息:异常值:(535,“身份验证数据不正确”)

任何人都可以给我一些我做错的建议吗?任何帮助表示赞赏.

最佳答案
以下设置:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = False
EMAIL_HOST = 'mail.yourdomain.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'no-reply@yourdomain.com'
EMAIL_HOST_PASSWORD = 'password'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

为我工作.我测试的django版本是1.8.8.
Bluehost smtp设置详细信息解释为here.

Python 教程 (7)—— 一文弄懂 Python 字符串操作 (上)| 字符串查找 | 字符串分割 | 字符串拼接 | 字符串替换

Python 教程 (7)—— 一文弄懂 Python 字符串操作 (上)| 字符串查找 | 字符串分割 | 字符串拼接 | 字符串替换

目录
  • 字符串简介
  • 字符串查找
    • 使用 in 关键字
    • 使用 find () 方法
    • 使用 index () 方法
    • 使用正则表达式
  • 字符串替换
    • 使用 replace () 方法
    • 使用正则表达式
    • 使用字符串模板
  • 字符串分割
  • 字符串拼接
    • 使用加号 (+) 运算符
    • 使用字符串的格式化方法
    • 使用 f-string(格式化字符串)
    • 使用字符串的 join () 方法

字符串简介

在计算机编程中,字符串是由字符组成的字节序列。在 Python 中,字符串是表示文本数据的数据类型,由一系列 Unicode 字符组成。字符串可以包含字母、数字、标点符号、空格以及其他特殊字符。实际工作当中,接触最多的可能就是字符串了。

字符串也是 Python 中最基本的类型,Python 中的字符串类型可以使用引号括起来。可以使用单引号、双引号或三引号来定义字符串。

str1 = ''Hello''
str2 = "World"
str3 = """Python"""

可以使用索引运算符([])来访问字符串中的单个字符。字符串的第一个字符索引为 0,最后一个字符索引为 - 1,可以使用负数进行倒序访问。例如:

str = "Hello, World!"
print(str[0])      # 输出 ''H''
print(str[-1])     # 输出 ''!''

字符串还可以通过加号(+)进行拼接,例如:

str1 = "Hello"
str2 = "World"
str3 = str1 + " " + str2
print(str3)   # 输出 ''Hello World''

Python 提供了丰富的字符串方法,用于处理字符串的操作,例如转换大小写、查找、替换等。还有格式化字符串的方法,用来替换占位符以生成特定格式的字符串。字符串类型说简单很简单,因为就单纯的字符串变化,说复杂也很复杂,结合其他相关类型,真的可以变化莫测。

字符串查找

在 Python 中,字符串查找是非常基础的功能,有几种常用的方法可以用来查找字符串中的子串或特定字符:

使用 in 关键字

使用 in 关键字。可以判断一个字符串是否包含另一个子串,这种方式简单方便,在编程当中经常会被用到。

str = "Hello, World!"
if "Hello" in str:
   print("包含 ''Hello''")
else:
   print("不包含 ''Hello''")

使用 find () 方法

使用 find() 方法。可以返回子串在字符串中第一次出现的索引值。如果找不到子串,返回 -1。

str = "Hello, World!"
index = str.find("World")
if index != -1:
   print("子串 ''World'' 的索引值为", index)
else:
   print("未找到子串 ''World''")

使用 index () 方法

index() 方法与 find() 方法类似,但是如果找不到子串,会抛出 ValueError 异常。

str = "Hello, World!"
try:
   index = str.index("World")
   print("子串 ''World'' 的索引值为", index)
except ValueError:
   print("未找到子串 ''World''")

使用正则表达式

Python 提供了 re 模块,可以使用正则表达式来进行复杂的字符串匹配与查找操作,需要说明的是正则表达式的用法千变万化,需要根据实际情况来使用。

import re

str = "Hello, World!"
pattern = r"World"
match = re.search(pattern, str)

if match:
   print("找到子串 ''World''")
   start_index = match.start()
   end_index = match.end()
   print("子串的起始索引为", start_index)
   print("子串的结束索引为", end_index)
else:
   print("未找到子串 ''World''")

上面就是一些常用的字符串查找的方法,可以根据需求选择合适的方法。需要注意的是,这些方法都是区分大小写的。如果想要进行大小写不敏感的查找,可以通过将字符串转换为统一的大小写来实现。

字符串替换

在一些编程当中,字符串替换是非常常见的操作,在 Python 中,可以使用不同的方法来替换字符串中的特定子串或字符,下面是一些常用的方法。

使用 replace () 方法

replace() 方法可以替换字符串中的所有匹配子串为新的子串。

str = "Hello, World!"
new_str = str.replace("World", "Python")
print(new_str)  # 输出 "Hello, Python!"

replace() 方法还可以指定替换的次数,只替换前几个匹配项。

str = "Hello, World!"
new_str = str.replace("l", "L", 2)
print(new_str)  # 输出 "HeLLo, World!"

使用正则表达式

可以利用 re 模块的 sub() 函数来使用正则表达式替换匹配的子串。使用正则表达式可以更灵活地进行替换操作,例如根据匹配结果动态替换内容。

import re

str = "Hello, World!"
new_str = re.sub(r"World", "Python", str)
print(new_str)  # 输出 "Hello, Python!"

使用字符串模板

使用字符串模板可以更加直观地进行替换,将需要替换的部分使用占位符表示。可以在字符串模板中定义多个占位符,并通过 format() 方法传入对应的值进行替换。

template = "Hello, {name}!"
new_str = template.format(name="Python")
print(new_str)  # 输出 "Hello, Python!"

字符串分割

字符串分割是指将一个字符串按照特定标记或规则将其拆分成多个子字符串的过程。将一个字符串分割成多个部分可以方便地处理和操作字符串的不同部分。在字符串分割过程中,需要指定一个分隔符或分割规则来确定拆分的位置。分隔符可以是一个字符,也可以是一个字符串。

假设有一个字符串 "Hello,World!",想将其分割为两部分,可以使用逗号作为分隔符,分割 "Hello" 和 "World!" 两个子字符串。

在 Python 中,你可以使用字符串的 split() 方法来分割字符串。这个方法会根据指定的分隔符将字符串分割成多个子字符串,并返回一个包含这些子字符串的列表。在 split() 方法中,你可以传入一个分隔符作为参数,如果不指定分隔符,默认以空格作为分隔符。

# 分割以空为分隔符的字符串
str1 = "Hello World"
split = str1.split()
print(split_result)  # Output: [''Hello'', ''World'']

 分割以逗号为分隔符的字符串
str = "Apple, Banana, Orange"
split_result = str2.split(", ")
print(split_result)  # Output: [''Apple'', ''Banana'', ''Orange'']

# 分割以换行符为分隔符的字符串
str3 = "Line 1\nLine 2\nLine 3"
split_result = str3.split("\n")
print(split_result)  # Output: [''Line 1'', ''Line 2'', ''Line 3'']

字符串拼接

字符串拼接看起来好像很简单,但是如果需要按照某种规则来拼接的话,可能也是需要一些方法的。在 Python 中,你可以使用多种方式进行字符串的拼接。

使用加号 (+) 运算符

使用加号 (+) 运算符,这是最简单的字符串拼接方法,直接通过 (+) 运算符将两个字符串拼接起来。

str1 = "Hello"
str2 = "World!"
result = str1 + "," + str2
print(result)  # 输出: Hello,World!

使用字符串的格式化方法

字符串的格式化方法通过占位符 {} 插入变量或表达式的值,并使用 format() 方法传递要换的内容。format() 方法可以接受多个参数,按照传入的顺序替换占位符。

str1 = "Hello"
str2 = "World!"
result = "{},{}".format(str1, str2)
print(result)  # 输出: Hello,World!

使用 f-string(格式化字符串)

f-string 是 python 新引入的一种字符串格式化的简便方法,它在字符串前加上 f 前缀。在 f-string 中,可以直接在花括号 {} 中引用变量、表达式或函数调用,并将其值插入到字符串中。

str1 = "Hello"
str2 = "World!"
result = f"{str1},{str2}"
print(result)  # 输出: Hello,World!

使用字符串的 join () 方法

join () 方法可以将一个可迭代对象中的元素连接成一个新的字符串。它的工作原理是在指定的分隔符上使用调用该方法的字符串作为粘合剂,将可迭代对象中的每个元素连接起来。在示例中," ".join([str1, str2]) 使用空格作为分隔符将列表 [str1, str2] 中的元素连接起来。

str1 = "Hello"
str2 = "World!"
result = ",".join([str1, str2])
print(result)  # 输出: Hello,World!

需要注意的是,使用加号 (+) 和 join 进行字符串拼接时,需要保证所有操作数都是字符串类型。如果有其他类型的对象,需要先将其转换为字符串再进行拼接。而使用字符串的格式化方法和 f-string 则可以直接将其他类型的对象插入到字符串中。

更多精彩内容,请关注同名公众:一点 sir(alittle-sir)

关于即使我的文件有我要查找的字符串,我仍然通过 python 收到错误电子邮件的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Python Gmail API:如何批量下载电子邮件附件和电子邮件?、Python SQL 脚本 - 如何发送有错误的电子邮件、python – 使用Bluehost电子邮件服务器的Django电子邮件配置、Python 教程 (7)—— 一文弄懂 Python 字符串操作 (上)| 字符串查找 | 字符串分割 | 字符串拼接 | 字符串替换等相关知识的信息别忘了在本站进行查找喔。

本文标签:

上一篇Vue 3 双向绑定 Composition API 与 Firestore 文档字段(vue双向绑定使用)

下一篇Python请求代理错误无法连接(python请求代理错误无法连接服务器)