【问题标题】:Send email based on print output - Python根据打印输出发送电子邮件 - Python
【发布时间】:2020-04-23 12:30:06
【问题描述】:

我编写了一个脚本,它将检查特定格式的 .docx 文件格式,并在打印功能上给我输出。

import glob

if glob.glob('//gbhfrd01/directorates/Business Support/Test/john//Python/*.docx'):
    print("File exist")
else:
    print("File not exist")

我想根据打印功能的输出发送电子邮件。例如,如果“文件不存在”发送电子邮件至 abc@test.com。

我在网上看到了如何使用 python 发送电子邮件,但我不知道如何根据打印功能的输出发送电子邮件。

对此的任何帮助都会非常有用。

【问题讨论】:

  • 如果您已经知道如何发送电子邮件,只需在else 中添加发送命令,打印后...
  • 请在@JeevanRao 的回答下方查看我的评论,您将使用它...

标签: python python-3.x python-2.7


【解决方案1】:

import glob,ssl,smtplib

def send_mail(message=None):
    port = 587
    smtp_server = "smtp.gmail.com"
    sender_email = "my@gmail.com"
    receiver_email = "your@gmail.com"
    password = "password"

    context = ssl.create_default_context()
    with smtplib.SMTP(smtp_server, port) as server:
        server.starttls(context=context)
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message)


if glob.glob('//gbhfrd01/directorates/Business Support/Test/john//Python/*.docx'):
    print("File exist")
else:
    print("File not exist")
    send_mail("File doesn't exist")

【讨论】:

  • 您应该告诉他在他正在使用的 gmail 帐户上启用安全性较低的应用程序 (myaccount.google.com/lesssecureapps?pli=1),否则它将无法正常工作并使用 (Python>=3.6)
  • 在启用安全性较低的应用程序后出现错误,因为第 4 行端口 = 587 ^ IndentationError: expected an indented block
  • 移除了端口 = 587 后的制表符空间
  • 有什么方法可以在不使用密码登录的情况下发送电子邮件。我使用的是我们办公室的本地 smtp 服务器而不是 gmail?
【解决方案2】:

这样做:

导入全局

if glob.glob('//gbhfrd01/directorates/Business Support/Test/john//Python/*.docx'):
    msg = "File exist"
    print(msg)
else:
    msg = "File not exist"
    print(msg)

if msg == "File not exist":
    # Write your email send logic here 

由于在函数的 else 块中打印“文件不存在”,因此它自己编写了电子邮件逻辑

 if glob.glob('//gbhfrd01/directorates/Business Support/Test/john//Python/*.docx'):
        print("File exist")
    else:
        print("File not exist")

        # Write your email logic here

【讨论】:

    【解决方案3】:

    您的代码已准备好执行您想要的操作。

    如果您想在“文件不存在”的情况下发送电子邮件,只需在 print("file not exist") 下写下您的电子邮件代码,如下所示:

    import glob
    
    if glob.glob('//gbhfrd01/directorates/Business Support/Test/john//Python/*.docx'):
        print("File exist")
    else:
        print("File not exist")
        write your code here which sends the email.
    

    如果您希望在“文件存在”时发送电子邮件,请将您的代码放在“打印(“文件存在”)下,如下所示:

    import glob
    
    if glob.glob('//gbhfrd01/directorates/Business Support/Test/john//Python/*.docx'):
        print("File exist")
        write your code here which sends the email.
    
    else:
        print("File not exist")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多