1

我正在尝试创建一个程序,该程序将发送和发送电子邮件,同时还将电子邮件的主题行和发送日期/时间记录到文本文件中。这是我到目前为止所拥有的。

def send_email():
    from exchangelib import Credentials, Account, Message, Mailbox, UTC_NOW
    import time

    credentials = Credentials('my@email', 'password')
    account = Account('my@email', credentials=credentials, autodiscover=True)

    m = Message(
                account=account,
                subject='Test Subject',
                body='Test Body',
                to_recipients=[
                    Mailbox(email_address='my@email')
                ])
    text_file = open("Output.txt", "w")
    text_file.write(time.strftime("%H:%M:%S"))
    text_file.close()
    m.send()

send_email()

按照目前写的,程序会发送一封邮件(给我自己测试),并会在当前时间登录一个txt文件(Output.txt)。我要输出的是:

Subject:"Test Subject" Date: 4/12/2019 Time: 13:45:09

*将日期和时间替换为发送的日期和时间。

当然我还有一些路要走,我开始对如何做到这一点的格式感到困惑,因为我是 Python 新手。是否有可能完成所有这些并将其打印在一行上?还是必须在多行上打印?我该怎么做呢?

4

2 回答 2

1

您需要添加额外的写入语句才能输出额外的信息。最好使用with块来处理文件的打开和关闭,而不是手动进行。学到更多。

例子:

def send_email():
    from exchangelib import Credentials, Account, Message, Mailbox, UTC_NOW
    import time

    credentials = Credentials('my@email', 'password')
    account = Account('my@email', credentials=credentials, autodiscover=True)

    subject = 'Test Subject'
    m = Message(
        account=account,
        subject=subject,
        body='Test Body',
        to_recipients=[
            Mailbox(email_address='my@email')
        ])

    with open("Output.txt", "w") as text_file:
        text_file.write("Subject: ")
        text_file.write(subject)
        text_file.write(" ")
        text_file.write("Date: ")
        text_file.write(time.strftime("%d/%m/%Y"))
        text_file.write(" ")
        text_file.write("Time: ")
        text_file.write(time.strftime("%H:%M:%S"))
        text_file.close()
        text_file.close()

    m.send()


send_email()

输出: Subject: Test Subject Date: 12/04/2019 Time: 18:49:13

于 2019-04-12T17:51:14.820 回答
1

首先,将写入模式更改为a代替,w因为使用w只会清除文件的所有先前内容。使用a,新数据被追加到文件中。只需将您的写入部分替换为:

with open("Output.txt", "a") as f:

此外,要以您的格式写入数据,请先创建字符串,然后一次性写入:

final_log = "Subject: {subject} Date: {date} Time: {time}\n".format(
    subject=subject, date=time.strftime("%d/%m/%Y"), time=time.strftime("%H:%M:%S")
)
f.write(final_log)
于 2019-04-12T18:06:43.033 回答