【问题标题】:Saving to .msg file in Python, or alternatively, sending mail to the file system在 Python 中保存到 .msg 文件,或者将邮件发送到文件系统
【发布时间】:2016-01-19 01:15:00
【问题描述】:

我正在使用emails 库发送邮件,但我还需要将其保存为.msg 文件。我做了一些研究,还阅读了 msg 格式规范,偶然发现了this SO answer,它显示了如何将邮件发送到C# 中的文件系统,我想知道在 Python 中是否也可以。

【问题讨论】:

    标签: python email


    【解决方案1】:

    这是可能的,而且很容易。让我们假设msg 是一个先前编写的包含所有标题和内容的消息,并且您希望将其写入文件对象out。你只需要:

    gen = email.generator.Generator(out)  # create a generator
    gen.flatten(msg)   # write the message to the file object
    

    完整示例:

    import email
    
    # create a simple message
    msg = email.mime.text.MIMEText('''This is a simple message.
    And a very simple one.''')
    msg['Subject'] = 'Simple message'
    msg['From'] = 'sender@sending.domain'
    msg['To'] = 'rcpt@receiver.domain'
    
    # open a file and save mail to it
    with open('filename.elm', 'w') as out:
        gen = email.generator.Generator(out)
        gen.flatten(msg)
    

    filename.elm 的内容是:

    Content-Type: text/plain; charset="us-ascii"
    MIME-Version: 1.0
    Content-Transfer-Encoding: 7bit
    Subject: Simple message
    From: sender@sending.domain
    To: rcpt@receiver.domain
    
    This is a simple message.
    And a very simple one.
    

    【讨论】:

    • 谢谢。我从我的emails 实例创建了一个email 实例并且它有效,但是有没有办法将它保存为msg 而不是eml?我尝试将with open('filename.elm', 'w') 更改为with open('filename.msg', 'w'),但(如预期的那样)outlook 无法打开该文件。
    • @DeepSpace msg 格式是二进制专有格式。使用它的唯一合理方法是通过 Outlook 自动化。在 SO 中搜索 [python] outlook msg file 给出了 this question 可以给你一些提示。我无法进一步帮助您,因为我已经几十年没有使用 Outlook。
    【解决方案2】:

    它在 Python 中是可行的,我尝试了以下代码,它将 Outlook 消息保存为文件夹中的 .msg。 注意:确保outlook对目标文件夹有写权限,默认目标文件夹是Python脚本的位置

    from win32com.client import Dispatch
    
    outlook = Dispatch("Outlook.Application").GetNamespace("MAPI") 
    inbox = outlook.GetDefaultFolder(6)
    messages = inbox.items
    for msg in messages:
      name = msg.subject
      name = str(name)
      name = name + ".msg"
      msg.saveas(name)
    

    【讨论】:

      【解决方案3】:

      是的,这是可能的。 有用于这些目的的模块,它被称为MSG PY。 例如:

      from independentsoft.msg import Message
      from independentsoft.msg import Recipient
      from independentsoft.msg import ObjectType
      from independentsoft.msg import DisplayType
      from independentsoft.msg import RecipientType
      from independentsoft.msg import MessageFlag
      from independentsoft.msg import StoreSupportMask
      
      message = Message()
      
      recipient1 = Recipient()
      recipient1.address_type = "SMTP"
      recipient1.display_type = DisplayType.MAIL_USER
      recipient1.object_type = ObjectType.MAIL_USER
      recipient1.display_name = "John Smith"
      recipient1.email_address = "John@domain.com"
      recipient1.recipient_type = RecipientType.TO
      
      recipient2 = Recipient()
      recipient2.address_type = "SMTP"
      recipient2.display_type = DisplayType.MAIL_USER
      recipient2.object_type = ObjectType.MAIL_USER
      recipient2.display_name = "Mary Smith"
      recipient2.email_address = "Mary@domain.com"
      recipient2.recipient_type = RecipientType.CC
      
      message.subject = "Test"
      message.body = "Body text"
      message.display_to = "John Smith"
      message.display_cc = "Mary Smith"
      message.recipients.append(recipient1)
      message.recipients.append(recipient2)
      message.message_flags.append(MessageFlag.UNSENT)
      message.store_support_masks.append(StoreSupportMask.CREATE)
      
      message.save("e:\\message.msg")
      

      【讨论】:

      • 请注意,根据模块创建者的网站 (independentsoft.de/msgpy/index.html),这不是免费软件。通过 PIP 安装会为您提供 30 天有效期的“评估版”。
      【解决方案4】:

      我认为这个问题的答案(但问题不是很清楚,部分在 cmets 中)是:

       import email
       from email.message import EmailMessage
      

      如果msg 是使用msg = EmailMessage() 创建的并填充了适当的调用(请参阅https://docs.python.org/3/library/email.examples.html),则可以使用msg 保存

      with open('mymessage.msg', 'wb') as f:
                  f.write(bytes(msg))
      

      并且可以使用以下方法恢复该文件:

       with open('mymessage.msg', 'rb') as fp:
             msg = email.message_from_binary_file(fp)            
      

      【讨论】:

        【解决方案5】:

        根据 python 的官方示例 - https://docs.python.org/3/library/email.examples.html 可以将电子邮件保存为 .msg 文件,然后再加载。

        from email.message import EmailMessage
        from email.parser import BytesParser
        
        # Create the base text message.
        msg = EmailMessage()
        msg['Subject'] = "Ayons asperges pour le déjeuner"
        msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
        msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
                     Address("Fabrette Pussycat", "fabrette", "example.com"))
        msg.set_content("""\
        Salut!
        
        Cela ressemble à un excellent recipie[1] déjeuner.
        
        [1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
        
        --Pepé
        """)
        
        # Make a local copy of what we are going to send.
        with open('outgoing.msg', 'wb') as f:
            f.write(bytes(msg))
        
        # Load local copy of email
        with open('outgoing.msg', 'rb') as fp:
            loaded_msg = BytesParser(policy=policy.default).parse(fp)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-09-11
          • 1970-01-01
          • 2011-02-07
          • 2022-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多