发送电子邮件后尝试将电子邮件主题和日期时间打印到txt文件

时间:2019-04-12 17:43:51

标签: python email time exchangelib

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

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的新手,我开始对如何操作的格式感到困惑。是否可以完成所有这些操作并将其打印在一行上?还是必须在多行上打印?我应该怎么做?

2 个答案:

答案 0 :(得分:1)

您需要添加其他write语句才能输出其他信息。也最好使用with块来处理文件的打开和关闭,而不要手动进行。 Learn More.

示例:

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

答案 1 :(得分: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)